Floyd算法
Floyd算法
弗洛伊德算法,用来计算多源最短路径(任意两个点之间的最短路径)
符号描述
- D(i,j)
- 节点i到节点j的最短距离
- N(i,j)
- 节点i到节点j的下一跳节点
思维
- 如果某个节点位于起点到终点的最短路径上
- D(i,j)=D(i,k)+D(k,j)
- 如果某个节点不位于起点到终点的最短路径上
- D(i,j)<D(i,k)+D(k,j)
Java
public class Floyd { private int [][]graph; private int size; private int[][] d; private int[][] n; public Floyd(int[][] graph) { this.graph = graph; size=graph.length; d=new int[size][size]; n=new int[size][size]; for (int i=0;i<size;i++) for (int j=0;j<size;j++){ //拷贝graph d[i][j]=graph[i][j]; n[i][j]=j; } cal(); } private void cal() { //经过点 for (int through = 0; through < size; through++){ //d的遍历 for (int start = 0; start < size; start++) { //通过点和起点重合 if (start == through) continue; for (int end = 0; end < size; end++) { //起点和终点重合或通过点和终点重合 if ( start == end || end == through) continue; int distance = d[start][through] + d[through][end]; if (distance < d[start][end]) { d[start][end] = distance; n[start][end] = through; } } } } } public void display(int start,int end){ String result=""+start; while (n[start][end]!=end){ result+="->"+n[start][end]; start=n[start][end]; } result+="->"+end; System.out.println(result); } public static void main(String[] args) { int INF=Integer.MAX_VALUE/2; int[][] graph=new int[][]{ {INF,-1,3,INF,INF}, {INF,INF,3,2,2}, {INF,INF,INF,INF,INF}, {INF,1,5,INF,INF}, {INF,INF,INF,INF,-3} }; Floyd floyd=new Floyd(graph); floyd.display(0,4); } }
相关推荐
Masimaro 2020-06-14
燕哥带你学算法 2020-05-31
rein0 2020-05-03
lixiaotao 2020-04-26
horizonheart 2020-04-18
RememberMePlease 2020-04-18
ustbfym 2020-03-03
chenfei0 2020-02-09
Oudasheng 2020-01-31
畅聊架构 2020-01-19
路漫 2020-01-17
wuxiaosi0 2019-12-20
燃灬初者 2019-12-17
风吹夏天 2019-12-07
Happyunlimited 2019-11-12
Happyunlimited 2019-11-01
LITElric 2019-09-08
风和日丽 2019-09-08
草堂 2010-10-21