-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDijkstraAlgo.java
53 lines (46 loc) · 1.59 KB
/
DijkstraAlgo.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
import java.util.*;
public class Solution {
public static ArrayList < Integer > dijkstra(ArrayList< ArrayList < Integer > > vec, int vertices, int edges, int source){
//To Store the result
ArrayList<Integer> result = new ArrayList<>();
for(int i=0;i<vertices;i++){
result.add(Integer.MAX_VALUE);
}
//Adjacency List
ArrayList<ArrayList<Node>> adjList = new ArrayList<>();
for(int i=0;i<vertices;i++){
adjList.add(new ArrayList<Node>());
}
result.set(0,0);
for(ArrayList<Integer> ve : vec){
adjList.get(ve.get(0)).add(new Node(ve.get(1),ve.get(2)));
adjList.get(ve.get(1)).add(new Node(ve.get(0),ve.get(2)));
}
//Priority Queue to keep track of min cost
PriorityQueue<Node> queue = new PriorityQueue<Node>(vertices,new Node());
queue.offer(new Node(0,0));
while(!queue.isEmpty()){
Node temp = queue.poll();
for(Node x : adjList.get(temp.v)){
if(result.get(temp.v) + x.cost< result.get(x.v)){
result.set(x.v,(result.get(temp.v) + x.cost));
queue.offer(new Node(x.v,result.get(x.v)));
}
}
}
return result;
}
}
class Node implements Comparator<Node>{
int v;
int cost;
Node(){}
Node(int _v,int _cost){
v = _v;
cost = _cost;
}
@Override
public int compare(Node a,Node b){
return a.cost-b.cost;
}
}