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
| class Solution { int N = 10000; Graph[] g = new Graph[N]; int[] dist = new int[N]; public int networkDelayTime(int[][] times, int N, int K) { int m = times.length; for(int i = 0; i < times.length; i++){ int a = times[i][0]; int b = times[i][1]; int c = times[i][2]; g[i] = new Graph(a, b, c); }
bellman(g, N, K, m);
int result = Integer.MIN_VALUE; for(int i = 1; i <= N; i++){ result = Math.max(result, dist[i]); }
return result == 1000000000 ? -1 : result; }
public void bellman(Graph[] g, int N, int K, int m){ Arrays.fill(dist, 1000000000);
dist[K] = 0;
for(int i = 1; i < N; i++){ int[] copy = Arrays.copyOf(dist, dist.length); for(int j = 0; j < m; j++){ int a = g[j].a; int b = g[j].b; int c = g[j].c; dist[b] = Math.min(dist[b], copy[a]+c); } } } }
class Graph{ public int a; public int b; public int c; public Graph(int a,int b, int c){ this.a = a; this.b = b; this.c = c; } }
|