Google News
logo
Algorithm - Interview Questions
What about Djikstra's algorithm pseudocode?
We need to maintain the path distance of every vertex. We can store that in an array of size v, where v is the number of vertices.
 
We also want to be able to get the shortest path, not only know the length of the shortest path. For this, we map each vertex to the vertex that last updated its path length.
 
Once the algorithm is over, we can backtrack from the destination vertex to the source vertex to find the path.
 
A minimum priority queue can be used to efficiently receive the vertex with least path distance.
function dijkstra(G, S)
    for each vertex V in G
        distance[V] <- infinite
        previous[V] <- NULL
        If V != S, add V to Priority Queue Q
    distance[S] <- 0
	
    while Q IS NOT EMPTY
        U <- Extract MIN from Q
        for each unvisited neighbour V of U
            tempDistance <- distance[U] + edge_weight(U, V)
            if tempDistance < distance[V]
                distance[V] <- tempDistance
                previous[V] <- U
    return distance[], previous[]
Advertisement