All-Pairs Shortest Path Algorithm
There is a simple dynamic programming method for finding the shortest
path between any two nodes. It works as follows:
- Start out with the graph in the form of an adjacency matrix.
- For each k:
- for each pair i,j where i,j are not k.
- compare the length of
the edge from i to j with the sum of the length of the edge from i to k
and the edge from k to j.
- if the sum of
the i to k and k to j edge is shorter, set the "shortest" path from i
to j to this sum and remember k
- end for
- If we have repeated this for every k we will have the
shortest path in each spot and we will know how we got there.
Example:
Edge/Edge
|
0
|
1
|
2
|
3
|
4
|
0
|
0
|
1
|
1000
|
2
|
4
|
1
|
1
|
0
|
78
|
6
|
3
|
2
|
1000
|
78
|
0
|
2
|
4
|
3
|
2
|
6
|
2
|
0
|
1
|
4
|
4
|
3
|
4
|
1
|
0
|
After doing the algorithm above, we get:
Edge/Edge
|
0
|
1
|
2
|
3
|
4
|
0
|
0
|
1
|
4,3
|
2
|
3,3
|
1
|
1
|
0
|
5,3
|
3,0
|
3
|
2
|
4,3
|
5,3
|
0
|
2
|
3,3
|
3
|
2
|
3,0
|
2
|
0
|
1
|
4
|
3,3
|
3
|
3,3
|
1
|
0
|