Menu
Coddy logo textTech

Pseudo Code

Lesson 4 of 9 in Coddy's Dijkstra's Algorithm - Graph Algorithms course.

dijkstra(n, edges, source):
   dist = [INF, INF, ...]; dist[source] = 0
   visited = all false
   repeat n times:
      u = unvisited vertex with smallest dist (none reachable -> stop)
      visited[u] = true
      for each edge (a -> b, weight w):
         if a == u and dist[u] + w < dist[b]:
            dist[b] = dist[u] + w
   replace every remaining INF with -1
   return dist
  • INF is just a number larger than any real distance (for example 1000000000).
  • Picking the smallest-dist unvisited vertex each round is the greedy heart of Dijkstra. Scanning the flat edge list to relax keeps the code simple and works in every language.

Try it yourself

This lesson doesn't include a code challenge.

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Dijkstra's Algorithm - Graph Algorithms