How to use Java to implement Floyd's algorithm
Floyd's algorithm is an algorithm used to find the shortest path between any two vertices. It uses the idea of dynamic programming, through Continuously update the value of the shortest path to find the optimal solution. This article will introduce how to use the Java programming language to implement Floyd's algorithm and give specific code examples.
public class FloydAlgorithm { public static void floyd(int[][] graph) { int n = graph.length; // 初始化最短路径矩阵 int[][] dist = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dist[i][j] = graph[i][j]; } } // 更新最短路径矩阵 for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (dist[i][k] != Integer.MAX_VALUE && dist[k][j] != Integer.MAX_VALUE && dist[i][k] + dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k] + dist[k][j]; } } } } // 输出最短路径矩阵 for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(dist[i][j] + " "); } System.out.println(); } } public static void main(String[] args) { int[][] graph = { {0, 5, Integer.MAX_VALUE, 10}, {Integer.MAX_VALUE, 0, 3, Integer.MAX_VALUE}, {Integer.MAX_VALUE, Integer.MAX_VALUE, 0, 1}, {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 0} }; floyd(graph); } }
In the above code, we define a FloydAlgorithm class , the floyd method is used to implement the Floyd algorithm. In the main method, we define the adjacency matrix graph of an example graph and call the floyd method to solve the shortest path matrix.
The above is the detailed content of How to implement Floyd's algorithm using java. For more information, please follow other related articles on the PHP Chinese website!