- Notifications
You must be signed in to change notification settings - Fork 363
Expand file tree
/
Copy pathdial_algorithm.java
More file actions
Latest commit
81 lines (74 loc) · 2.2 KB
/
Copy pathdial_algorithm.java
File metadata and controls
81 lines (74 loc) · 2.2 KB
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
importjava.util.*;
publicclassdial_algorithm {
staticfinalintINF = Integer.MAX_VALUE;
privateintV;
privateArrayList<ArrayList<Tuple>> adj;
publicdial_algorithm(intv) {
this.V = v;
this.adj = newArrayList<ArrayList<Tuple>>();
for (inti = 0; i < v; i++)
this.adj.add(newArrayList<Tuple>());
}
publicvoidAddEdge(intu, intv, intw) {
adj.get(u).add(newTuple(v, w));
adj.get(v).add(newTuple(u, w));
}
publicvoidshortestPath(intsrc, intW) {
int[] dist = newint[V];
Arrays.fill(dist, INF);
ArrayList<Integer>[] B = newArrayList[W * V + 1];
for (inti = 0; i < W * V + 1; i++)
B[i] = newArrayList<Integer>();
B[0].add(src);
dist[src] = 0;
intidx = 0;
while (true) {
while (B[idx].size() == 0 && idx < W * V)
idx++;
if (idx == W * V)
break;
intu = B[idx].get(0);
B[idx].remove(0);
for (Tuplei : adj.get(u)) {
intv = i.v;
intweight = i.w;
intdu = dist[u];
intdv = dist[v];
if (dv > du + weight) {
dist[v] = du + weight;
dv = dist[v];
B[dv].add(0, v);
}
}
}
System.out.println("Distance from Source");
for (inti = 0; i < V; ++i)
System.out.println(i + "\t\t" + dist[i]);
}
staticclassTuple {
intv, w;
Tuple(intv, intw) {
this.v = v;
this.w = w;
}
}
publicstaticvoidmain(String[] args) {
intV = 9;
dial_algorithmg = newdial_algorithm(V);
g.AddEdge(0, 1, 4);
g.AddEdge(0, 7, 8);
g.AddEdge(1, 2, 8);
g.AddEdge(1, 7, 11);
g.AddEdge(2, 3, 7);
g.AddEdge(2, 8, 2);
g.AddEdge(2, 5, 4);
g.AddEdge(3, 4, 9);
g.AddEdge(3, 5, 14);
g.AddEdge(4, 5, 10);
g.AddEdge(5, 6, 2);
g.AddEdge(6, 7, 1);
g.AddEdge(6, 8, 6);
g.AddEdge(7, 8, 7);
g.shortestPath(0, 14);
}
}