CBMS-2017-10
题目来源:[[文字版题库/CBMS/2017#Problem 10|2017#Question 10]] 日期:2024-07-29 题目主题:CS-图-最短路径
Solution
(1) Directed Graph Analysis
Given the directed graph, we will:
(A) Construct the adjacency matrix.
(B) Construct the shortest distance matrix.
Let’s start with the directed graph:
graph TD;
1 --> 2;
2 --> 3;
3 --> 1;
3 --> 6;
4 --> 1;
5 --> 1;
5 --> 4;
6 --> 4;
7 --> 5;
7 --> 6;
(A) Adjacency Matrix
The adjacency matrix for the graph is a square matrix where the element is 1 if there is an edge from vertex to vertex , and 0 otherwise.
(B) Shortest Distance Matrix
The matrix will be computed using the Floyd-Warshall algorithm. The element is the shortest distance from vertex to vertex .
-
Initialize with:
- if
- if there is an edge from to
- otherwise
-
Update using the Floyd-Warshall algorithm:
The final matrix is:
(2) General Case Analysis
(A) Matrix in terms of
The matrix is computed by considering paths that may pass through the vertex 1.
(B) Recursive Calculation
To find from , use:
(C) Algorithm for All-Pair Shortest Paths
The Floyd-Warshall algorithm is suitable for computing all-pair shortest distances:
-
Initialize where is 0 if , 1 if there is an edge , and otherwise.
-
Update using:
for all vertices from 1 to .
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 because it involves three nested loops, each running times.
知识点
重点词汇
- adjacency matrix 邻接矩阵
- shortest distance 最短距离
- edge 边
- vertex 顶点
参考资料
- 《算法导论》 第 25 章 最短路径算法