Pseudo Code for Dijkstra's Algorithm

Adjacency Matrix Version

Determining the Shortest Paths from a Single Start Node to All Other Nodes



sample directed graph


INPUT: An n x n matrix EdgeLength, which represents a directed graph G with n nodes. The names of the nodes are 1, 2, ..., n. Node 1 is the start node. EdgeLength[i][j] = zero if i=j. If i ≠ j, and if an edge of G exists from node i to node j, then EdgeLength[i][j] = the length of the edge. If i ≠ j, and there is no edge in G from node i to node j, then EdgeLength[i][j] = INF, a special value that is larger than the sum of all the lengths of all edges in G.

OUTPUT: Two 1 x n matrices, Dist and BackPoint.

THE PSEUDO-CODE:


             /* S is the set of nodes reached so far */
    Initialize a set C = {2, 3, ... , n} ; /* C is the complement of S */
    For i from 1 to n
       {
          Initialize Dist[i] = EdgeLength[1,i] ; /* the matrix top row */
          Initialize BackPoint[i] = 1 ;
       }

             /* The greedy loop */
    Do n-2 times
       {
           ν = some element of C with smallest value of Dist[ν] ;

             /* The 'magic' of the algorithm is that Dist[ν] is 
                now the length of the shortest path from 1 to ν
                (or INF, if there's no path from 1 to ν). */

           C = C-{ν} ; /* Delete ν from C }  */

                 /*  Check for better paths that use ν.  */
           For each ω in C such that there is an edge ν-->ω
              {
                  If Dist[ω] > Dist[ν] + EdgeLength[ν,ω]
                  Then
                      {
                          Dist[ω] = Dist[ν] + EdgeLength[ν,ω] ;
                          BackPoint[ω] = ν ;
                      }
              }
       }
       Return Dist and BackPoint as the output ;