public class Dijkstra {
static final int M = 10000;
static void dijkstra(int[][] edges, int s) {
int vertexs = edges.length;
// dist
int[] d = new int[vertexs];
// π
int[] p = new int[vertexs];
boolean[] visited = new boolean[vertexs];
for(int i = 0; i < vertexs; i++) {
d[i] = M;
p[i] = -1;
}
d[s] = 0;
for(int cnt = 0; cnt < vertexs; cnt++) {
int u = -1;
//extract-min
int min = Integer.MAX_VALUE;
for(int i = 0; i < vertexs; i++) {
if(!visited[i] && d[i] < min) {
min = d[i];
u = i;
}
}
//union
visited[u] = true;
//relaxation
for(int v = 0; v < edges[u].length; v++) {
if(d[v] > (d[u] + edges[u][v])) {
d[v] = d[u] + edges[u][v];
p[v] = u;
}
}
}
//print
for(int i = 0; i < vertexs; i++) {
char u = (char)('A' + s);
char v = (char)('A' + i);
if (d[i] < M) {
System.out.printf("%c -> %c (%d) : ", u, v, d[i]);
StringBuilder sb = new StringBuilder();
int j = i;
if(s != i)
sb.append(v);
while (p[j] != -1) {
sb.insert(0, (char) ('A' + p[j]) + " - ");
j = p[j];
}
System.out.println(sb.toString());
} else {
System.out.printf("%c -> %c (∞) : \n", u, v);
}
}
}
public static void main(String[] args) {
int[][] edges = {
{0, M, M, M, M, M, 9},
{20, 0, 10, 30, M, M, M},
{M, M, 0, M, 5, M, 18},
{M, M, M, 0, M, M, M},
{M, M, M, 12, 0, M, 15},
{M, M, M, M, 8, 0, 10},
{M, M, 18, M, M, M, 0}
};
dijkstra(edges, 1);
}
}
输出结果:
B -> A (20) : B - A
B -> B (0) :
B -> C (10) : B - C
B -> D (27) : B - C - E - D
B -> E (15) : B - C - E
B -> F (∞) :
B -> G (28) : B - C - G