Shortest Paths and Dijkstra's Algorithm CS 110: Data Structures and Algorithms First Semester,
Single-Source Shortest Paths ► Given a weighted graph G and a source vertex v in G, determine the shortest paths from v to all other vertices in G ► Path length: sum of all edges in path ► Useful in road map applications (e.g., Google maps or map quest) for example
Dijkstra’s Algorithm ► Solves the single-source shortest path problem ► Involves keeping a table of current shortest path lengths from a source vertex (initialize to infinity for all vertices except v, which has length 0)
Dijkstra’s Algorithm ► Repeatedly select the vertex u with shortest path length, and update other lengths by considering the path that passes through that vertex ► Stop when all vertices have been selected
Dijkstra’s Algorithm ► Can make use of a priority queue to facilitate selection of shortest lengths ► Need to refine the data structure to allow the updating of key values ► Time complexity: O(n+m) or O(n 2 log n) ► O(n 2 ) if computation of minimum is simplified
MIA JFK PVD BOS DFW SFO LAX BWI ORD Dijkstra’s Algorithm
MIA JFK PVD BOS DFW SFO LAX BWI ORD ∞ ∞ ∞ ∞ ∞ ∞ ∞ ∞ 0 Dijkstra’s Algorithm
MIA JFK PVD BOS DFW SFO LAX BWI ORD ∞ 621 ∞ ∞ 946 ∞ 184 ∞ 0 Dijkstra’s Algorithm
MIA JFK PVD BOS DFW SFO LAX BWI ORD ∞ 621 ∞ ∞ 946 ∞ 184 ∞ 0 Dijkstra’s Algorithm
MIA JFK PVD BOS DFW SFO LAX BWI ORD ∞ ∞ Dijkstra’s Algorithm
MIA JFK PVD BOS DFW SFO LAX BWI ORD ∞ ∞ Dijkstra’s Algorithm
MIA JFK PVD BOS DFW SFO LAX BWI ORD ∞ ∞ Dijkstra’s Algorithm
MIA JFK PVD BOS DFW SFO LAX BWI ORD ∞ ∞ Dijkstra’s Algorithm
MIA JFK PVD BOS DFW SFO LAX BWI ORD ∞ Dijkstra’s Algorithm
MIA JFK PVD BOS DFW SFO LAX BWI ORD ∞ Dijkstra’s Algorithm
MIA JFK PVD BOS DFW SFO LAX BWI ORD ∞ Dijkstra’s Algorithm
MIA JFK PVD BOS DFW SFO LAX BWI ORD ∞ Dijkstra’s Algorithm
MIA JFK PVD BOS DFW SFO LAX BWI ORD Dijkstra’s Algorithm
MIA JFK PVD BOS DFW SFO LAX BWI ORD Dijkstra’s Algorithm
MIA JFK PVD BOS DFW SFO LAX BWI ORD Dijkstra’s Algorithm
MIA JFK PVD BOS DFW SFO LAX BWI ORD Dijkstra’s Algorithm
Pseudo-Code: Dijkstra function Dijkstra( Graph g, Vertex source ) for each vertex v in g dist[v] <-- infinity previous[v] <-- undefined dist[source] <-- 0 Q <-- the set of all nodes in Graph while Q is not empty u <-- vertex in Q with smallest dist[] if dist[u] == infinity break remove u from Q for each neighbor v of u alt = dist[u] + dist_between( u, v ) if alt < dist[v] dist[v] = alt previous[v] = u return dist[]