Dial Algorithm
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:
7. The position of a temporarily labeled vertex in the buckets is updated accordingly when the distance
label of a vertex changes.
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
67 public static void main(String[] args)
68 {
69 int V = 9;
70 Graph g = new Graph(V);
71 g.AddEdge(0, 1, 4);
72 g.AddEdge(0, 7, 8);
73 g.AddEdge(1, 2, 8);
74 g.AddEdge(1, 7, 11);
75 g.AddEdge(2, 3, 7);
76 g.AddEdge(2, 8, 2);
77 g.AddEdge(2, 5, 4);
78 g.AddEdge(3, 4, 9);
79 g.AddEdge(3, 5, 14);
80 g.AddEdge(4, 5, 10);
81 g.AddEdge(5, 6, 2);
82 g.AddEdge(6, 7, 1);
83 g.AddEdge(6, 8, 6);
84 g.AddEdge(7, 8, 7);
85
86 // maximum weighted edge - 14
87 g.shortestPath(0, 14);
88 }
THANK YOU