forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReachableNodesInSubdividedGraph.java
59 lines (41 loc) · 1.64 KB
/
ReachableNodesInSubdividedGraph.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
class Solution {
public int reachableNodes(int[][] edges, int maxMoves, int n) {
int[][] graph = new int[n][n];
for (int[] edge : graph) {
Arrays.fill(edge, -1);
}
for (int[] edge: edges) {
// source -> end = Distance / Intermediatory nodes
graph[edge[0]][edge[1]] = edge[2];
graph[edge[1]][edge[0]] = edge[2];
}
int ans = 0;
boolean[] visited = new boolean[n];
// Comparator on the basis of max moves possible
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> (b[1] - a[1]));
pq.add(new int[] {0, maxMoves});
while (!pq.isEmpty()) {
int[] nearestEl = pq.poll();
int nearestNodeId = nearestEl[0];
int maxMovesRemaining = nearestEl[1];
if (visited[nearestNodeId]) {
continue;
}
visited[nearestNodeId] = true;
// beacuse you are visiting the curr node
ans++;
for (int nei = 0; nei < n; nei++) {
if (graph[nearestNodeId][nei] != -1) {
if (!visited[nei] && maxMovesRemaining >= graph[nearestNodeId][nei] + 1) {
pq.add(new int[]{nei, maxMovesRemaining - graph[nearestNodeId][nei] - 1});
}
int movesCost = Math.min(maxMovesRemaining, graph[nearestNodeId][nei]);
graph[nei][nearestNodeId] -= movesCost;
graph[nearestNodeId][nei] -= movesCost;
ans += movesCost;
}
}
}
return ans;
}
}