Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Dijkstra Algorithm

Dijkstra's Algorithm requires a graph and source vertex to work. The algorithm is purely based
on greedy approach and thus finds the locally optimal choice(local minima in this case) at each
step of the algorithm.
In this algorithm each vertex will have two properties defined for it-
 Visited property:- This property represents whether the vertex has been visited or not.
 Path property:- This property stores the value of the current minimum path to the vertex.
Current minimum path means the shortest way in which we have reachedthis vertex till now.
Algorithm
1. Mark the source node with a current distance of 0 and the rest with infinity.
2. Set the non-visited node with the smallest current distance as the current node, lets say C.
3. For each neighbour N of the current node C: add the current distance of C with the weight of
the edge connecting C-N. If it is smaller than the current distance of N, set it as the new
current distance of N.
4. Mark the current node C as visited.
5. Go to step 2 if there are any nodes are unvisited.
Implementaions for Dijkstra's Algorithm

def minDistance(self, dist, sptSet):


min = intmax
for u in range(self.V):
if dist[u] < min and sptSet[u] == False:
min = dist[u]
min_index = u

return min_index

def dijkstra(self, src):

dist = [intmax] * self.V


dist[src] = 0
sptSet = [False] * self.V
for cout in range(self.V):
x = minDistance(dist, sptSet)
sptSet[x] = True

for y in range(self.V):
if self.graph[x][y] > 0 and sptSet[y] == False and dist[y] > dist[x] + self.graph[x][y]:
dist[y] = dist[x] + self.graph[x][y]
self.printSolution(dist)

Dijkstra Algorithm Time Complexity

The time complexity of dijkstra's algorithm with adjacency matrix is O(V^2) where as the time

complexity can be reduced to O((V+E)logV) using adjacency list.

You might also like