迭代过程:重复执行以下步骤,直到所有节点都被标记为已访问(即已找到最短路径): a. 从未访问的节点中选择距离最小的节点作为当前节点。 b. 对于当前节点的每个邻接节点,计算通过当前节点到达邻接节点的路径长度之和。如果该路径长度小于邻接节点的当前最短路径长度,则更新最短路径长度为新的路径长度。 c. 标记当前节点为已访问。
staticfinalintINF= Integer.MAX_VALUE; staticint[][] cost = null; staticint[] dis = null; staticboolean[] vis = null; /** * n nodes * m edges * s start node * t target node */ staticint n, m, s, t; /** * u start * v end * w weight */ staticint u, v, w;
publicstaticvoidmain(String[] args) { Scannerscanner=newScanner(System.in); n = scanner.nextInt(); m = scanner.nextInt(); cost = newint[n][n]; for (inti=0; i < n; i++) { Arrays.fill(cost[i], INF); } for (inti=0; i < m; i++) { u = scanner.nextInt(); v = scanner.nextInt(); w = scanner.nextInt(); cost[u][v] = w; } s = 0; t = n - 1; dijkstra(); System.out.println(dis[t]);
}
publicstaticvoiddijkstra() { dis = newint[n]; vis = newboolean[n]; for (inti=0; i < n; i++) { dis[i] = INF; vis[i] = false; } dis[s] = 0; for (; ; ) { intk= -1; intmin= INF; // 寻找最小值的偏移 for (intj=0; j < n; j++) { if (!vis[j] && dis[j] < min) { min = dis[j]; k = j; } } // 已经全部访问过了 if (k == -1) { break; } // 访问过的打上标记 vis[k] = true; for (intj=0; j < n; j++) { if (!vis[j] && cost[k][j] != INF && dis[k] + cost[k][j] < dis[j]) { dis[j] = dis[k] + cost[k][j]; } } } } }