Let G = (V,E) be a directed graph in which each edge (i, j) has a nonnegative length l[i, j]. If there is no edge from vertex i to vertex j, then l[i, j] = ∞. The problem is to find the distance from each vertex to all other vertices, where the distance from vertex x to vertex y is the length of a shortest path from x to y.
Assuming there is no negative length circuit in the directed graph.
For simplicity, we will assume that V = {1, 2, . . ., n}. Let i and j be two different vertices in V . Define d**k(i,j) to be the length of a shortest path from i to j that does not pass through any vertex in {k + 1, k + 2, . . . , n}. Thus, for example, d**0(i,j) = l[i, j], d**1(i,j) is the length of a shortest path from i to j that does not pass through any vertex except possibly vertex 1, d**2(i,j) is the length of a shortest path from i to j that does not pass through any vertex except possibly vertex 1 or vertex 2 or both, and so on. Then, by definition, d**n(i,j) is the length of a shortest path from i to j, i.e., the distance from i to j. So we can use n + 1 matrices D0,D1, . . . , Dn of dimension n × n to compute the lengths of the shortest constrained paths, i.e., Dk= d**k(i,j)
By the definition of d**k(i,j), we have:
Vi, A list of vertices with each vertex serial number no greater than k, Vj
We can divide all such paths into two disjoint subsets: paths in one subset do not pass the k-th vertex, while paths in the other subset pass the k-th vertex. In the first subset, the serial number of vertices contained in the path will not be greater than k-1. According to our definition, the length of the shortest path is d**k-1(i,j).
For the second subset, we have:
Vi, vertices with serial number ≤ k-1, Vk , vertices with serial number ≤ k-1, Vj .
In other words, each path is composed of two paths: a path from Vi to Vk, where the number of each vertex in the path is not greater than k-1; A path from Vk to Vj, where the number of each vertex in the path is not greater than k-1
任意两个节点之间的最短路径。假设输入是一个 n x n 的矩阵,表示有向图中每条边的长度,其中矩阵的第 i 行第 j 列表示从节点 i 到节点 j 的边的长度。输出是一个矩阵 D,其中 D[i, j] 表示从节点 i 到节点 j 的最短路径长度。
-
首先,将输入矩阵复制到一个新的矩阵 D 中。
-
然后,使用三重循环来计算最短路径长度。外层循环 k 从 1 到 n,表示允许经过节点 k 的路径。中间两层循环 i 和 j 分别表示起点和终点节点,计算经过节点 k 的路径和不经过节点 k 的路径哪个更短,更新矩阵 D。
-
最后,矩阵 D 中的值就是从节点 i 到节点 j 的最短路径长度。
D0中的位置(1,1)的0意思是第1个节点到自己本身的距离 (1,2)中的2指的是横轴节点1到纵轴节点2的距离 (3,2)的∞则是横轴节点3到纵轴节点2没有路径则距离为∞
D1则发生了变化,所有路径可以经过节点1 距离可能发生变化的有
(2, 3) (3,2) 因为对角线距离不可能发生变化,而从节点1出发或从以节点1为终点都已经经过节点1也不会发生变化即横轴为1纵轴为1的距离都不会发生变化。
如何计算变化后的值(2,3)中看(2,1) (1,3)即横轴为2以及纵轴为3的节点中的没有发生变化且距离不为0的节点,距离之和9+8=17>6则距离不变;(3,2)中看(1,3)(2,1)的距离之和1+2=3<∞ 则距离之和取代原有距离 即(3,2)中的距离变为3
其中的原理是(2,1)即节点2到节点1距离 (1,3)节点1到节点3距离 其总和与原有节点2直接到节点3距离作比较 求出最短路径