Day 18 Dial Algorithm
Day 18 Dial Algorithm
Dial’s Algorithm
1. Maintains some buckets, numbered 0, 1, 2,…,wV.
4. Buckets 0, 1, 2,..wV are checked sequentially until the first non-empty bucket is
found. Each node contained in the first non-empty bucket has the minimum
distance label by definition.
5. One by one, these nodes with minimum distance labels are permanently labeled
and deleted from the bucket during the scanning process.
Dial’s Algorithm
6. Thus operations involving vertex include:
8. The process is repeated until all vertices are permanently labeled (or the distances
of all vertices are finalized).
1 import java.util.*;
2 public class Graph {
3 static final int INF = Integer.MAX_VALUE;
4 private int V;
5 private ArrayList<ArrayList<Tuple> > adj;
6 public Graph(int v){
7 this.V = v;
8 this.adj = new ArrayList<ArrayList<Tuple> >();
9 for (int i = 0; i < v; i++)
10 this.adj.add(new ArrayList<Tuple>());
11 }
12 public void AddEdge(int u, int v, int w){
13 adj.get(u).add(new Tuple(v, w));
14 adj.get(v).add(new Tuple(u, w));
15 }
16 public void shortestPath(int src, int W){
17 int[] dist = new int[V];
18 Arrays.fill(dist, INF);
19 ArrayList<Integer>[] B = new ArrayList[W * V + 1];
20 for (int i = 0; i < W * V + 1; i++)
21 B[i] = new ArrayList<Integer>();
22 B[0].add(src);
23 dist[src] = 0;
24 int idx = 0;
25 while (true) {
26 while (B[idx].size() == 0 && idx < W * V)
27 idx++;
28 if (idx == W * V)
29 break;
30 int u = B[idx].get(0);
31 B[idx].remove(0);
32 for (Tuple i : adj.get(u)) {
33 int v = i.v;
34 int weight = i.w;
35 int du = dist[u];
36 int dv = dist[v];
37 if (dv > du + weight) {
38 dist[v] = du + weight;
39 dv = dist[v];
40 B[dv].add(0, v);
41 }
42 }
43 }
44
45 System.out.println("Vertex Distance from Source");
46 for (int i = 0; i < V; ++i)
47 System.out.println(i + "\t\t" + dist[i]);
48 }
49 static class Tuple {
50 int v, w;
51 Tuple(int v, int w){
52 this.v = v;
53 this.w = w;
54 }
55 }
56 public static void main(String[] args){
57 Scanner s=new Scanner(System.in);
58 int V = s.nextInt();
59 Graph g = new Graph(V);
60 int e=s.nextInt();
61 int st,en,d;
62
63
64
65
66
67 for(int i=0; i<e; i++){
68 st=s.nextInt();
69 en=s.nextInt();
70 d=s.nextInt();
71 g.AddEdge(st,en,d);
72 }
73 g.shortestPath(0,e);
74 }
75 }
76
77
78
79
80
81
82
83
84
85
86
87
88
THANK YOU