常用十大算法(九)— 弗洛伊德算法
常用十大算法(九)— 弗洛伊德算法
博客说明
文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢!
介绍
- 弗洛伊德(Floyd)算法也是一种用于寻找给定的加权图中顶点间最短路径的算法
最短路径问题
- 胜利乡有7个村庄(A, B, C, D, E, F, G)
- 各个村庄的距离用边线表示(权) ,比如 A – B 距离 5公里
- 问:如何计算出各村庄到 其它各村庄的最短距离?
思路
- 设置顶点vi到顶点vk的最短路径已知为Lik,顶点vk到vj的最短路径已知为Lkj,顶点vi到vj的路径为Lij,则vi到vj的最短路径为:min((Lik+Lkj),Lij),vk的取值为图中所有顶点,则可获得vi到vj的最短路径
- 至于vi到vk的最短路径Lik或者vk到vj的最短路径Lkj,是以同样的方式获得
代码实现
package com.atguigu.floyd;
import java.util.Arrays;
public class FloydAlgorithm {
public static void main(String[] args) {
char[] vertex = { 'A', 'B', 'C', 'D', 'E', 'F', 'G' };
int[][] matrix = new int[vertex.length][vertex.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(vertex.length, matrix, vertex);
graph.floyd();
graph.show();
}
}
class Graph {
private char[] vertex;
private int[][] dis;
private int[][] pre;
public Graph(int length, int[][] matrix, char[] vertex) {
this.vertex = vertex;
this.dis = matrix;
this.pre = new int[length][length];
for (int i = 0; i < length; i++) {
Arrays.fill(pre[i], i);
}
}
public void show() {
char[] vertex = { '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(vertex[pre[k][i]] + " ");
}
System.out.println();
for (int i = 0; i < dis.length; i++) {
System.out.print("("+vertex[k]+"µ½"+vertex[i]+"µÄ×î¶Ì·¾¶ÊÇ" + dis[k][i] + ") ");
}
System.out.println();
System.out.println();
}
}
public void floyd() {
int len = 0;
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];
}
}
}
}
}
}
感谢
尚硅谷