bellman-ford算法
提交代码
class Solution {
public int networkDelayTime(int[][] times, int N, int K) {
int[][] graph = new int[N+1][N+1];
for(int i=0;i<N+1;i++)
Arrays.fill(graph[i], -1);
for(int[] t: times)
graph[t[0]][t[1]] =t[2];
int[] path=new int[N+1];
Arrays.fill(path, Integer.MAX_VALUE);
path[K] = 0;
Queue<Integer> nodes= new LinkedList<>();
nodes.offer(K);
while(nodes.size()>0) {
int curNode= nodes.poll();
for(int i=1;i<=N;i++) {
if(i==curNode||graph[curNode][i]==-1) continue;
int curPath = path[curNode]+graph[curNode][i];
if(curPath<path[i]) {
nodes.offer(i);
path[i] = curPath;
}
}
}
int maxPath = Integer.MIN_VALUE;
for(int i=1;i<=N;i++) {
if(i==K) continue;
if(path[i]==Integer.MAX_VALUE) return -1;
maxPath=path[i]>maxPath?path[i]:maxPath;
}
return maxPath;
}
}