2
public int networkBecomesIdle(int[][] edges, int[] patience) {3
int n = patience.length;5
// creating adjacency list6
ArrayList<ArrayList<Integer>> adj = new ArrayList<>();7
for (int i = 0; i < n; i++) {8
adj.add(new ArrayList<>());11
for (int[] edge : edges) {12
adj.get(edge[0]).add(edge[1]);13
adj.get(edge[1]).add(edge[0]);16
// getting the distance array using dijkstra algorithm17
int[] dist = dijkstra(adj);19
// variable to store the result22
// performing the calculations discussed above for each index23
for (int x = 1; x < n; x++) {26
int time = 2 * dist[x];30
// total number of messages the station will send until it receives the reply of first message31
int numberOfMessagesSent = (time) / p;33
// handling an edge case if round trip time is a multiple of patience example time =2435
// then the reply would be received at 24 therefore station will not send any message at t =38
numberOfMessagesSent--;41
// time of last message42
int lastMessage = numberOfMessagesSent * p;44
// updating the ans to store max of time at which the station becomes idle45
ans = Math.max(ans, lastMessage + 2 * dist[x] + 1);51
// simple dijkstra algorithm implementation52
private int[] dijkstra(ArrayList<ArrayList<Integer>> adj) {56
int[] dist = new int[n];57
boolean[] visited = new boolean[n];59
Arrays.fill(dist, Integer.MAX_VALUE);62
PriorityQueue<int[]> pq = new PriorityQueue<>((o1, o2) -> o1[1] - o2[1]);64
pq.add(new int[] {0, 0});66
while (!pq.isEmpty()) {67
int[] node = pq.remove();68
if (!visited[node[0]]) {69
visited[node[0]] = true;70
for (int nbr : adj.get(node[0])) {71
if (dist[nbr] > dist[node[0]] + 1) {72
dist[nbr] = dist[node[0]] + 1;73
pq.add(new int[] {nbr, dist[nbr]});