1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
| package graph;
import java.util.LinkedList; import java.util.List;
public class Floyd { private static final int N = 1000;
public static void main(String[] args) { char[] vertices = { 'A', 'B', 'C', 'D', 'E', 'F', 'G' };
int[][] distance = { { 0, 5, 7, N, N, N, 2 }, { 5, 0, N, 9, N, N, 3 }, { 7, N, 0, N, 8, N, N }, { N, 9, N, 0, N, 4, N }, { N, N, 8, N, 0, 5, 4 }, { N, N, N, 4, 5, 0, 6 }, { 2, 3, N, N, 4, 6, 0 }, };
int[][] path = new int[7][7]; for (int i = 0; i < path.length; i++) { for (int j = 0; j < path[0].length; j++) { path[i][j] = i; } }
final int len = distance.length; for (int v = 0; v < len; v++) { for (int i = 0; i < len; i++) { for (int j = 0; j < len; j++) { if (distance[i][v] + distance[v][j] < distance[i][j]) { distance[i][j] = distance[i][v] + distance[v][j]; path[i][j] = path[v][j]; } } } }
showDistance(distance, vertices); showPath(path, vertices);
System.out.println(getPath('D', 'C', path, vertices)); }
public static List<Character> getPath(char a, char b, int[][] path, char[] vertices) { List<Character> vs = new LinkedList<>(); int start = a - 'A'; int end = b - 'A';
while (end != start) { vs.add(0, vertices[end]); end = path[start][end]; } vs.add(0, vertices[start]);
return vs; }
private static void showDistance(int[][] distance, char[] vertices) { final int len = distance.length;
out(' '); for (int i = 0; i < len; i++) { out(vertices[i]); } for (int i = 0; i < len; i++) { System.out.println(); out(vertices[i]);
for (int j = 0; j < len; j++) { out(distance[i][j]); } } System.out.println(); System.out.println(); }
private static void showPath(int[][] path, char[] vertices) { final int len = path.length;
out(' '); for (int i = 0; i < len; i++) { out(vertices[i]); } for (int i = 0; i < len; i++) { System.out.println(); out(vertices[i]);
for (int j = 0; j < len; j++) { out(vertices[path[i][j]]); } } System.out.println(); System.out.println(); }
private static void out(int n) { System.out.printf("%5s", (n == N) ? "N" : n); } private static void out(char c) { System.out.printf("%5s", c); } }
|