-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDijsktra.java
134 lines (105 loc) · 2.15 KB
/
Dijsktra.java
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package algos;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.PriorityQueue;
import java.util.Scanner;
/*
* Input Sample
5 6
0 1 4
0 2 4
0 3 5
1 2 2
2 4 1
3 4 1
5 6
0 1 1
0 2 4
0 3 5
1 2 2
2 4 1
3 4 1
*/
class Dijkstra {
private ArrayList<ArrayList<Pair>> al = new ArrayList<>();
private PriorityQueue<Pair> queue = new PriorityQueue<>();
private Boolean[] visited;
private int[] dist;
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int n = sc.nextInt();
int m = sc.nextInt();
Dijkstra dObject = new Dijkstra();
dObject.initialize(n,m);
dObject.doDijkstra();
dObject.printResult();
sc.close();
}
private void printResult() {
// System.out.println("printing ans-----");
for(int d : dist){
System.out.println(d);
}
}
private void initialize(int n, int m) {
for(int i=0;i<n;i++){
al.add(new ArrayList<Pair>());
}
for(int i=0;i<m;i++){
int a = sc.nextInt();
int b = sc.nextInt();
int w = sc.nextInt();
al.get(a).add(new Pair(b,w));
al.get(b).add(new Pair(a,w));
}
visited = new Boolean[n];
for(int i=0;i<n;i++){
visited[i]=false;
}
dist = new int[n];
for(int i=0;i<n;i++){
dist[i]=Integer.MAX_VALUE;
}
dist[0]=0;
queue.add(new Pair(0,0));
}
private void doDijkstra(){
while(!queue.isEmpty()){
Pair current = queue.poll();
Iterator<Pair> itr = al.get(current.getV()).iterator();
while(itr.hasNext()){
Pair a = itr.next();
int x = dist[current.getV()] + a.getW();
if(x<dist[a.getV()]){
dist[a.getV()]=x;
queue.add(new Pair(a.getV(),x));
}
}
}
}
}
class Pair implements Comparable{
private int v;
private int w;
public Pair(int v, int w){
this.v=v;
this.w=w;
}
public int getV() {
return v;
}
public void setV(int v) {
this.v = v;
}
public int getW() {
return w;
}
public void setW(int w) {
this.w = w;
}
@Override
public int compareTo(Object o) {
Pair p = (Pair)o;
return this.w - p.getW();
}
}