Translation Notice
This article was machine-translated using DeepSeek-R1.
- Original Version: Authored in Chinese by myself
- Accuracy Advisory: Potential discrepancies may exist between translations
- Precedence: The Chinese text shall prevail in case of ambiguity
- Feedback: Technical suggestions regarding translation quality are welcomed
Preface
In graphs, when requiring distances between any two points, we can use Floyd
($\mathcal O(N^3)$;))and Dijkstra ($\mathcal O(NM\log M)$:)). For relatively small data ranges (typically vertex count $N\le 150$), Floyd’s algorithm is suitable. This article explains the principles, implementation, and extended applications of Floyd’s algorithm.
If there are any shortcomings, please feel free to provide feedback. Thank you!
Principle
$$ f(x,y)= \begin{cases} 0 & (x=y) \\ G[x][y] & (G[x][y]\ne0)\\ +\infty & (x\ne y,G[x][y]=0) \end{cases} $$
where $G$ is the adjacency matrix of the graph, $G[x][y]$ represents the edge weight from vertex $x$ to $y$, and $0$ indicates no edge between $x$ and $y$.
Next, consider enumerating intermediate points $k$ and calculating the shortest path via the route $x\to k\to y$. The pseudocode is:
|
|
At this point, the algorithm concludes, and the final $f(x,y)$ represents the shortest path from $x$ to $y$.
Note: When the given graph is undirected, for any $(x,y)$, $G[x][y]=G[y][x]$, so $f(x,y)=f(y,x)$. The computation process can be adjusted (e.g., using f[k][x]+f[k][y]
). However, for directed graphs, strictly follow the order in the pseudocode!
Code
The code for Floyd
’s algorithm can be submitted on Luogu B3647. Below is the AC code for this problem (note edge-based input):
|
|
Extension
Now the question arises: How to output the result path? The method is simple. Similar to Dijkstra
but slightly different, let $\text{path}(x, y)$ be a point on the shortest path from $x\to y$. When updating $f(x,y)$ during state transition if $f(x,k)+f(k,y) < f(x,y)$, not only update $f(x,y)$ but also set $\text{path}(x,y):=k$. Finally, recursively output the result.
Problem Statement
Given a simple undirected graph with $N$ vertices and $M$ edges, for every pair $(i,j)$ ($1\le i < j\le N$), output every vertex on the shortest path from $i\to j$.
Sample
Input:
|
|
Output:
|
|
Code
|
|
Note: Since the length of each path won’t exceed $N$, the overall time complexity remains $\mathcal O(N^3)$.
Epilogue
Summary: Floyd
’s algorithm has a time complexity of $\mathcal O(N^3)$ and is convenient to implement. If you found this helpful, please give a like/share/follow—thank you for your support!