The shortest path problem comes up in a lot of different places. The minimization metric changes though.
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.
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.
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:
Then, you choose the unvisited node with the shortest distance from the origin. Update all distances. Repeat until all nodes are visited.
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:
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.