classSolution{/*
Step 1: Create a Map of start and end nodes with weight
1 -> {2,1},{3,2}
2 -> {4,4},{5,5}
3 -> {5,3}
4 ->
5 ->
Step 2: create a result array where we will keep track the minimum distance to rech end of the node from start node
Step 3: Create a Queue and add starting position with it's weight and add it's reachable distance with increament of own't weight plus a weight require to reach at the end node from start node.
We keep adding and removing pairs from queue and updating result array as well.
Step 4: find the maximum value from result array:
*/publicintnetworkDelayTime(int[][] times,int n,int k){// Node -> adjacent nodesMap<Integer,Map<Integer,Integer>> map =newHashMap<>();// Construct adjacency listfor(int[] time : times){int source = time[0];int dest = time[1];int weight = time[2];
map.putIfAbsent(source,newHashMap<>());
map.get(source).put(dest, weight);}// Create result array to keep track the shortest pathint[] dis =newint[n +1];Arrays.fill(dis,Integer.MAX_VALUE);
dis[k]=0;// 0 distance from source node to itself// BFS for Dijkstra's algo.Queue<int[]> q =newLinkedList();
q.add(newint[]{k,0});// Add the sourcewhile(!q.isEmpty()){int[] cur = q.poll();int curNode = cur[0];int curWeight = cur[1];// Iterate the adjacent nodes of the current nodefor(int next : map.getOrDefault(curNode,newHashMap<>()).keySet()){int nextWeight = map.get(curNode).get(next);if(curWeight + nextWeight < dis[next]){
dis[next]= curWeight + nextWeight;
q.add(newint[]{next, curWeight + nextWeight});}}}// Find the resultint res =0;for(int i =1; i <= n;++i){
res =Math.max(res, dis[i]);}return res ==Integer.MAX_VALUE?-1: res;}}