Floyd shortest path [learning algorithm]
Preface
2023-9-26 18:09:58
The following content is from "[Learning Algorithm]"
and is for learning and communication purposes only.
copyright
Delete the following words when publishing on other platforms.
This article was first published on the CSDN platform.
The author is CSDN@日星月云.
The homepage of the blog is https://blog.csdn.net/qq_51625007
. Delete the above words when publishing on other platforms.
recommend
none
Floyd shortest path
public class FloydAlgorithm {
private static final int INF = 99999;
public void floyd(int[][] graph, int n) {
int[][] dist = new int[n][n];
int i, j, k;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
dist[i][j] = graph[i][j];
}
}
for (k = 0; k < n; k++) {
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
// 输出最短路径矩阵
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (dist[i][j] == INF) {
System.out.print("INF ");
} else {
System.out.print(dist[i][j] + " ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
//有向图
int[][] graph = {
{
0, 5, INF, 10},
{
INF, 0, 3, INF},
{
INF, INF, 0, 1},
{
INF, INF, INF, 0}
};
int n = 4;
FloydAlgorithm algorithm = new FloydAlgorithm();
algorithm.floyd(graph, n);
}
}
at last
2023-9-26 18:12:15
We all have a bright future
I wish you all the best in your postgraduate entrance exams, I wish you all success
in your work, I wish you all get what you wish for, like, collect and follow.