acwing-849. Dijkstra求最短路 I
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
| import java.util.*; class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[][] g = new int[501][501]; int[] dist = new int[501]; boolean[] st = new boolean[501]; for(int i = 1; i < g.length; i++){ Arrays.fill(g[i], 1000000000); } for(int i = 1; i<= m; i++){ int a = sc.nextInt(); int b = sc.nextInt(); int c = sc.nextInt(); g[a][b] = Math.min(g[a][b], c); } System.out.println(dijkstra(n, g, dist, st)); } public static int dijkstra(int n, int[][] g, int[] dist, boolean[] st){ Arrays.fill(dist, 1000000000); dist[1] = 0; for(int i = 1; i <= n; i++){ int t = -1; for(int j = 1; j<= n; j++){ if(!st[j] && (t==-1 || dist[j]<dist[t])){ t = j; } } st[t] = true; for(int k = 1; k <= n; k++){ dist[k] = Math.min(dist[k], dist[t] + g[t][k]); } } return dist[n]==1000000000 ? -1 : dist[n]; } }
|