-
Notifications
You must be signed in to change notification settings - Fork 0
/
p146.java
95 lines (76 loc) · 2.95 KB
/
p146.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
/*Given a weighted, undirected and connected graph of V vertices and an adjacency list adj where adj[i] is a list of lists containing two integers where the first integer of each list j denotes there is edge between i and j , second integers corresponds to the weight of that edge . You are given the source vertex S and You to Find the shortest distance of all the vertex's from the source vertex S. You have to return a list of integers denoting shortest distance between each node and Source vertex S.
Note: The Graph doesn't contain any negative weight cycle.
Example 1:
Input:
V = 2
adj [] = {{{1, 9}}, {{0, 9}}}
S = 0
Output:
0 9
Explanation:
The source vertex is 0. Hence, the shortest
distance of node 0 is 0 and the shortest
distance from node 1 is 9.
Example 2:
Input:
V = 3, E = 3
adj = {{{1, 1}, {2, 6}}, {{2, 3}, {0, 1}}, {{1, 3}, {0, 6}}}
S = 2
Output:
4 3 0
Explanation:
For nodes 2 to 0, we can follow the path-
2-1-0. This has a distance of 1+3 = 4,
whereas the path 2-0 has a distance of 6. So,
the Shortest path from 2 to 0 is 4.
The shortest distance from 0 to 1 is 1 .
Your Task:
You don't need to read input or print anything. Your task is to complete the function dijkstra() which takes the number of vertices V and an adjacency list adj as input parameters and Source vertex S returns a list of integers, where ith integer denotes the shortest distance of the ith node from the Source node. Here adj[i] contains a list of lists containing two integers where the first integer j denotes that there is an edge between i and j and the second integer w denotes that the weight between edge i and j is w.
Expected Time Complexity: O(V2).
Expected Auxiliary Space: O(V2).
Constraints:
1 ≤ V ≤ 1000
0 ≤ adj[i][j] ≤ 1000
1 ≤ adj.size() ≤ [ (V*(V - 1)) / 2 ]
0 ≤ S < V*/
class Solution{
static class Pair implements Comparable<Pair>{
int node;
int cost;
public Pair(int n,int c){
this.node=n;
this.cost=c;
}
@Override
public int compareTo(Pair p2){
return this.cost-p2.cost;
}
}
static int[] dijkstra(int V, ArrayList<ArrayList<ArrayList<Integer>>> adj, int S){
PriorityQueue<Pair> pq=new PriorityQueue<>();
boolean vis[]=new boolean[V];
int dist[]=new int[V];
for(int i=0;i<V;i++){
if(i!=S){
dist[i]=Integer.MAX_VALUE;
}
}
pq.add(new Pair(S,0));
while(!pq.isEmpty()){
Pair curr=pq.poll();
int u=curr.node;
if(vis[u]==false){
vis[u]=true;
for(ArrayList<Integer> al:adj.get(curr.node)){
int v=al.get(0);
int wt=al.get(1);
if(dist[u]+wt<dist[v]){
dist[v]=dist[u]+wt;
pq.add(new Pair(v, dist[v]));
}
}
}
}
return dist;
}
}