弗洛伊德算法(Floyd)
Posted bingbug
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了弗洛伊德算法(Floyd)相关的知识,希望对你有一定的参考价值。
弗洛伊德算法和迪杰斯特拉算法类似,是计算一个图中各个顶点之间的最短路径,每一个顶点都是出发顶点
记录两个顶点的距离,如果有经过某一顶点所得到的距离比直接连接这两个顶点的距离小则更新,否则不变
实现为:使用双层循环当中间顶点不变,出发和终点的点进行循环,最后使用一层循环更新中间顶点,总共使用三层循环,时间复杂度为n^3(理解实现简单复杂度都不会太低,想快点就去理解使用迪杰斯特拉算法吧)
import java.util.Arrays; public class FloydAlgorithm { public static void main(String[] args) { char[] vertexs = {‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘, ‘G‘}; int[][] matrix = new int[vertexs.length][vertexs.length]; final int N = 65535; matrix[0] = new int[]{0, 5, 7, N, N, N, 2}; matrix[1] = new int[]{5, 0, N, 9, N, N, 3}; matrix[2] = new int[]{7, N, 0, N, 8, N, N}; matrix[3] = new int[]{N, 9, N, 0, N, 4, N}; matrix[4] = new int[]{N, N, 8, N, 0, 5, 4}; matrix[5] = new int[]{N, N, N, 4, 5, 0, 6}; matrix[6] = new int[]{2, 3, N, N, 4, 6, 0}; Graph graph = new Graph(vertexs.length, matrix, vertexs); graph.show(); graph.floyd(); graph.show(); } } class Graph { private char[] vertex;//顶点数组 private int[][] dis;//距离表 private int[][] pre;//前驱节点表 /** * @param lenght 大小 * @param matrix 邻接矩阵 * @param vertex 顶点数组 */ public Graph(int lenght, int[][] matrix, char[] vertex) { this.vertex = vertex; this.dis = matrix; this.pre = new int[lenght][lenght]; for (int i = 0; i < lenght; i++) { Arrays.fill(pre[i], i); } } //显示 pre dis public void show() { char[] vertexs = {‘A‘, ‘B‘, ‘C‘, ‘D‘, ‘E‘, ‘F‘, ‘G‘}; for (int k = 0; k < dis.length; k++) { for (int i = 0; i < dis.length; i++) { System.out.print(vertexs[pre[k][i]] + " "); } System.out.println(); for (int i = 0; i < dis.length; i++) { System.out.print("(" + vertexs[k] + "->" + vertexs[i] + " " + dis[k][i] + ") "); } System.out.println(); System.out.println(); } } public void floyd() { int len = 0; //对中间顶点遍历 k 是中间顶点的下标 for (int k = 0; k < dis.length; k++) { for (int i = 0; i < dis.length; i++) { for (int j = 0; j < dis.length; j++){ len = dis[i][k] + dis[k][j]; if (len < dis[i][j]){ dis[i][j] = len; pre[i][j] = pre[k][j]; } } } } } }
以上是关于弗洛伊德算法(Floyd)的主要内容,如果未能解决你的问题,请参考以下文章