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 60 61 62 63
| class Solution { int N = 110, M = 6010; int[] he = new int[N], e = new int[M], ne = new int[M], w = new int[M]; int[] dist = new int[N]; boolean[] vis = new boolean[N]; int n, k, idx; int INF = 0x3f3f3f3f; void add(int a, int b, int c) { e[idx] = b; ne[idx] = he[a]; he[a] = idx; w[idx] = c; idx++; } public int networkDelayTime(int[][] ts, int _n, int _k) { n = _n; k = _k; Arrays.fill(he, -1); for (int[] t : ts) { int u = t[0], v = t[1], c = t[2]; add(u, v, c); } dijkstra(); int ans = 0; for (int i = 1; i <= n; i++) { ans = Math.max(ans, dist[i]); } return ans > INF / 2 ? -1 : ans; } void dijkstra() { Arrays.fill(vis, false); Arrays.fill(dist, INF); dist[k] = 0; PriorityQueue<int[]> q = new PriorityQueue<>((a,b)->a[1]-b[1]); q.add(new int[]{k, 0}); while (!q.isEmpty()) { int[] poll = q.poll(); int id = poll[0], step = poll[1]; if (vis[id]) continue; vis[id] = true; for (int i = he[id]; i != -1; i = ne[i]) { int j = e[i]; if (dist[j] > dist[id] + w[i]) { dist[j] = dist[id] + w[i]; q.add(new int[]{j, dist[j]}); } } } } }
|