【leetcode】743. Network Delay Time

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;
    }
}

運行結果

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章