Giventimes, a list of travel times as directed edgestimes[i] = (u, v, w), whereuis the source node,vis the target node, andwis the time it takes for a signal to travel from source to target.
Now, we send a signal from a certain nodeK. How long will it take for all nodes to receive the signal? If it is impossible, return-1.
Note:
Nwill be in the range[1, 100].
Kwill be in the range[1, N].
The length oftimeswill be in the range[1, 6000].
All edgestimes[i] = (u, v, w)will have1 <= u, v <= Nand1 <= w <= 100.
2. Implementation
(1) BFS
classSolution {publicintnetworkDelayTime(int[][] times,int N,int K) {int[][] edge =newint[N +1][N +1];for (int[] e : edge) {Arrays.fill(e,Integer.MAX_VALUE); }for (int[] time : times) { edge[time[0]][time[1]] = time[2]; }int[] delay =newint[N +1];Arrays.fill(delay,Integer.MAX_VALUE); delay[K] =0;Queue<Integer> queue =newLinkedList<>();queue.add(K);while (!queue.isEmpty()) {int size =queue.size();Set<Integer> set =newHashSet<>();for (int i =0; i < size; i++) {int curNode =queue.remove();for (int nextNode =1; nextNode <= N; nextNode++) {if (edge[curNode][nextNode] !=Integer.MAX_VALUE&& delay[curNode] + edge[curNode][nextNode] < delay[nextNode]) {if (!set.contains(nextNode)) {set.add(nextNode);queue.add(nextNode); } delay[nextNode] = delay[curNode] + edge[curNode][nextNode]; } } } }int res =0;for (int i =1; i <= N; i++) { res =Math.max(res, delay[i]); }return res ==Integer.MAX_VALUE?-1: res; }}