Shortest path, part I – Dijkstra’s algorithm

Now that we have a way to represent graphs, we can discuss one of the most important problems in graph theory: the shortest path problem (SPP). More or less formally, we’ll define SPP as:

Given a weighted graph G(V,E), find the sequence P = {v0, v1, v2, …, v(n-1)}, vi ∈ V, from vertex V0 to vertex V(n-1), such that the list of edges EP = {(v0,v1), (v1,v2), … (v(n-2), v(n-1))} exists and the summation of costs of all elements e ∈ EP is the smallest possible.

In other words, find the less expensive (ergo “shortest”) path between two vertices.

The trivial solution is using BFS starting at vertex A and stopping when it reaches vertex B. However, BFS doesn’t look at the edge costs: it calculates the path with least edges, not the path with least total cost.

Although not necessarily the fastest, Dijkstra’s algorithm is probably the most popular way to solve the shortest path problem due to its simplicity and elegance. The algorithm relies heavily on priority queues, so make sure to take a look at that if you haven’t already.

Pseudocode

dist[from] = 0
for v : G 
      if v != source 
            dist[v] = infinity          
      prev[v] = -1
      PQ.add(v, dist[v])
while PQ.hasNext()                
      u = PQ.pop()             
      for each neighbor v of u
            alt = dist[u] + length(u, v) 
            if alt < dist[v]             
                  dist[v] = alt 
                  prev[v] = u
                  PQ.decrease_key(v,alt)
return prev

Continue reading “Shortest path, part I – Dijkstra’s algorithm”

Advertisements