We define the shortest distance from a vertex i to a vertex j on a graph as the number of edges in a path from i to j that contains the smallest number of edges, except that the shortest distance is +∞ when no such path exists and that it is 0 when i and j are identical.
(1) Let us consider the directed graph shown below.
(A) Show the adjacency matrix.
(B) Show a matrix S, whose element si,j is the shortest distance from a vertex i to a vertex j.
(2) Suppose we are given a simple directed graph G=(V,E), where the vertex set V={1,2,…,n} and E is the edge set. E is represented by a matrix D(0)=(di,j(0)), where
di,j(0)=⎩⎨⎧01+∞(if i=j)(if an edge i→j exists)(otherwise)
(A) Let Vi,j(k)={1,2,…,k}∪{i,j}. Let Ei,j(k) be the set of edges in E that start from and end at a vertex in Vi,j(k). Let di,j(k) be the shortest distance from a vertex i to a vertex j on a directed graph Gi,j(k)=(Vi,j(k),Ei,j(k)), and let D(k)=(di,j(k)). Express D(1) in terms of D(0).
(B) D(k+1) can be computed from D(k) as follows. Fill in the two blanks.
di,j(k+1)=min(di,j(k),ddd+ddd)
(C) Given G, show an algorithm to compute the all-pair shortest distances, and find its time complexity with regard to n.
我们将从顶点 i 到顶点 j 的最短距离定义为图中从 i 到 j 的包含最少边数的路径中的边数,除了当不存在这样的路径时最短距离为 +∞,以及当 i 和 j 相同时为 0。
The Floyd-Warshall algorithm is suitable for computing all-pair shortest distances:
Initialize D where di,j is 0 if i=j, 1 if there is an edge i→j, and +∞ otherwise.
Update D using: di,j=min(di,j,di,k+dk,j) for all vertices k from 1 to n.
Algorithm:
function FloydWarshall(V, E): let D be a |V| x |V| matrix of minimum distances for each vertex v in V: D[v][v] = 0 for each edge (u, v) in E: D[u][v] = 1 for each k from 1 to |V|: for each i from 1 to |V|: for each j from 1 to |V|: D[i][j] = min(D[i][j], D[i][k] + D[k][j]) return D
Time Complexity:
The time complexity of the Floyd-Warshall algorithm is O(∣V∣3) because it involves three nested loops, each running n times.