题解 | #单源最短路#
单源最短路
http://www.nowcoder.com/practice/9f15b34a2a944a7798a5340ff0dba8b7
public class Solution { public int findShortestPath(int n, int m, int[][] graph) { int[] dp = new int[n + 1]; Arrays.fill(dp, Integer.MAX_VALUE); dp[1] = 0; for (int i = 1; i <= n; i++) {//遍历中间节点 for (int j = 0; j < m; j++) { if (graph[j][0] == i) { int k = graph[j][1]; int path = -1;//记录中间节点为i的1~k的距离 if (dp[i] == Integer.MAX_VALUE) { path = Integer.MAX_VALUE; } else { path = dp[i] + graph[j][2];//1~i的距离+i~k的距离 } dp[k] = Math.min(dp[k], path);//更新1~k的距离 } } } if (dp[n] == Integer.MAX_VALUE) { return -1; } else { return dp[n]; } } }