每对顶点的最短路径 : 基本算法
2013-08-29 10:39
519 查看
public class AllPairsShortestPaths { static final int M = 10000; //unreachable //extend-shortest-path static int[][] extendShortestPath(int[][] L, int[][] W) { int[][] R = new int[L.length][L[0].length]; int n = L.length; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { R[i][j] = M; for(int k = 0; k < n; k++) { if(R[i][j] > (L[i][k] + W[k][j])) R[i][j] = L[i][k] + W[k][j]; } } } return R; } //slow-all-pairs-shortest-paths static void slowAllPairsShortestPaths(int[][] W) { int n = W.length; /* * D1 = W * max n - 1 edges * L(n-1) == L(n) == L(n + 1) */ int[][] L = W; for(int i = 2; i < n; i++) { L = extendShortestPath(L, W); } //print for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { System.out.printf("%c -> %c (%d) : \n", (char)('A' + i), (char)('A' + j), L[i][j]); } System.out.println(); } System.out.println(); } //faster-all-pairs-shortest-paths static void fasterAllPairsShortestPaths(int[][] W) { int n = W.length; /* * D1 = W * L(n-1) == L(n) == L(n + 1) */ int[][] L = W; int m = 1; while(m < n) { L = extendShortestPath(L, W); m = 2 * m; } //print for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { System.out.printf("%c -> %c (%d) : \n", (char)('A' + i), (char)('A' + j), L[i][j]); } System.out.println(); } System.out.println(); } public static void main(String[] args) { int[][] edges = { {0, 3, 8, M, -4}, {M, 0, M, 1, 7}, {M, 4, 0, M, M}, {2, M, -5, 0, M}, {M, M, M, 6, 0} }; System.out.println("slow-all-pairs-shortest-paths"); slowAllPairsShortestPaths(edges); System.out.println("faster-all-pairs-shortest-paths"); fasterAllPairsShortestPaths(edges); } }
相关文章推荐
- 每对顶点间的最短路径基本算法 --- 算法导论笔记
- 【算法导论】每对顶点之间的最短路径算法
- 设计一个算法,采用BFS方式输出图G中从顶点u到v的最短路径(不带权的无向连通图G采用邻接表存储)
- 弗洛伊德算法得到图中任意两个顶点之间的最短路径
- 用最基本的弗洛伊德算法求1到n的最短路径
- 所有顶点之间的最短路径算法:Floyd算法。
- FLOYD每对顶点间最短路径算法
- 经典算法之Floyd算法(求图中任意一对顶点间的最短路径)
- (Dijkstra)算法--按路径长度递增序产生各顶点最短路径
- 一个例子让你明白一个算法-Dijkstra(求源点到各顶点最短路径)
- 每对顶点的最短路径 : Johnson 算法
- 顶点间最短路径长度之探寻算法
- 每对顶点间的最短路径算法时间复杂度改进C++实现
- 顶点间最短路径长度之探寻算法
- 【Python排序搜索基本算法】之Dijkstra最短路径算法(Dijkstra's Shortest-Path Algorithm)
- 数据结构与算法:最短路径,拓扑排序的基本概念
- 最短路径顶点算法:最短路径之迪杰斯特拉(Dijkstra)算法Strut2教程-java教程
- 弗洛伊德算法求每一对顶点之间的最短路径
- 单源最短路径的基本算法 -- 算法导论笔记
- 求最短路径的三种基本算法