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
| class Solution { public int networkDelayTime(int[][] times, int n, int k) { int MAX = Integer.MAX_VALUE / 2;
int[][] grid = new int[n + 1][n + 1]; for (int[] g : grid) { Arrays.fill(g, MAX); } for (int[] time : times) { grid[time[0]][time[1]] = time[2]; }
int[] distance = new int[n + 1]; Arrays.fill(distance, MAX); distance[k] = 0;
boolean[] used = new boolean[n + 1];
for (int i = 1; i <= n; i++) { int nearest = -1; for (int j = 1; j <= n; j++) { if (!used[j] && (nearest == -1 || distance[j] < distance[nearest])) { nearest = j; } }
for (int j = 1; j <= n; j++) { int dist = grid[nearest][j]; distance[j] = Math.min(distance[j], distance[nearest] + dist); } used[nearest] = true; }
int time = Integer.MIN_VALUE; for (int i = 1; i <= n; i++) { time = Math.max(time, distance[i]); } return time == MAX ? -1 : time; } }
|