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
|
public class Greedy { static int N = 5, M = 1000; static int[][] c = new int[N + 1][N + 1]; static int[] dist = new int[N + 1]; static int[] prev = new int[N + 1];
public static void main(String[] args) { int v = 1; init(); Dijkstra(N, 1, dist, prev, c); System.out.println("输出:"); for (int i = 2; i <= N; i++) { System.out.println("从1出发到" + i + "的最短距离为:" + dist[i]); } System.out.println("======================="); for (int i = 2; i <= N; i++) { System.out.print("从1出发到" + i + "的最短路径为:"); Traceback(v, i, prev); System.out.println(" "); } }
public static void Dijkstra(int n, int v, int[] dist, int[] prev, int c[][]) { Boolean[] s = new Boolean[N + 1]; for (int i = 1; i <= n; i++) { dist[i] = c[v][i];
s[i] = false;
if (dist[i] == M) { prev[i] = 0; } else { prev[i] = v; } }
dist[v] = 0; s[v] = true;
for (int i = 1; i < n; i++) { int temp = M; int u = v;
for (int j = 1; j <= n; j++) { if ((!s[j]) && (dist[j] < temp)) { u = j; temp = dist[j]; } }
s[u] = true;
for (int j = 1; j <= n; j++) { if ((!s[j]) && (c[u][j] < M)) { int newdist = dist[u] + c[u][j]; if (newdist < dist[j]) { dist[j] = newdist; prev[j] = u; } } } } }
static void Traceback(int v, int i, int[] prev) { if (v == i) { System.out.print(i); return; } else { Traceback(v, prev[i], prev); System.out.print("-->" + i); }
}
public static void init() { for (int i = 1; i <= N; i++) { dist[i] = 0; for (int j = 1; j <= N; j++) { c[i][j] = M; } } c[1][2] = 10; c[1][4] = 30; c[1][5] = 100; c[2][3] = 50; c[3][5] = 10; c[4][5] = 60; c[4][3] = 20;
} }
|