Data Structures and Algorithms

Shortest Path Algorithms Dijkstra's Shortest Path and Floyd-Warshall

The shortest path problem comes up in a lot of different places. The minimization metric changes though.

  • Distance
  • Travel time
  • Number of stoplights
  • Etc

Problem Statement

Input: Edge weighted graph, and cost function for each edge.

Output: A path from one vertex to another vertex. You want to find the smallest path.

Single-source shortest path

Given an edge weighted graph, find the shortest path to every vertex. Dijkstra's algorithm does this.

In an unweighted graph, depth-first search is guaranteed to give a shortest path.

For edge weighted graphs, this gets really complicated for graphs with negative edge cycles. The best way will only get in that negative cycle and never reach the destination.

Dijkstra's Algorithm

This is a greedy algorithm for solving shortest path problems. This assumes non-negative weights. This algorithm finds the shortest path from our vertex to every other vertex.

Algorithm: For every vertex, keep track of:

  • Do we have a current shortest path to the new vertex?
  • What is the length of this path?
  • What is the parent of this node?

Then, you choose the unvisited node with the shortest distance from the origin. Update all distances. Repeat until all nodes are visited.

All-pairs shortest path problem

Let's say you want to find the shortest path from any node to any other node. One thing you could do is running Dijkstra's algorithm V times, or using Floyd's algorithm.

This is a dynamic programming method for solving the all-pairs shortest path problem on a dense graph. This uses an adjacency matrix, and solves it in time.

First, create the adjacency matrix. Add edge weights where needed, or infinity if there is no edge connection. For all the nodes 0 through k, you see if, for all paths, if adding the vertex into the path would make it shorter. That is, the minimum of:

  • D(i, j)
  • D(i, k) + D(k, j)

This makes it hard to track the paths to get back. Unlike Prim's algorithm and Dijkstra's, you have to go back and add some code to remember the paths.