问题
解决这样一类问题,起点确定的,可以有重边和自环的,各边权都为正数的稠密图的最短路问题
要素
g[][]邻接矩阵,存储图的信息st[]记录已经确定最短距离的点-
思路
dist[], st[]分别存储起点到各点的最短距离,各点最短距离是否已经确定 Arrays.fill[dist, INF]; dist[1] = 0for(i : 1~n)
遍历各个节点,找到t <- 不在st中的距离起点最近的点
st <- t加入该点到st
遍历t的临边,更新临点到起点的最短距离
模板
给定一个 n 个点 m 条边的有向图,图中可能存在重边和自环,所有边权均为正值。
请你求出 1 号点到 n 号点的最短距离,如果无法从 1 号点走到 n 号点,则输出 −1。
输入格式
第一行包含整数 n 和 m。
接下来 m 行每行包含三个整数 x,y,z,表示存在一条从点 x 到点 y的有向边,边长为 z。
输出格式
输出一个整数,表示 1 号点到 n 号点的最短距离。
如果路径不存在,则输出 −1。
数据范围
1≤n≤500,
1≤m≤105,
图中涉及边长均不超过10000。
输入样例:
3 31 2 22 3 11 3 4
输出样例:
3
代码:
import java.util.*;public class Main {static final int N = 510;static int[][] g = new int[N][N];static int[] dist = new int[N];static boolean[] st = new boolean[N];static int n, m;public static void main(String[] args) {Scanner sc = new Scanner(System.in);n = sc.nextInt();m = sc.nextInt();for (int i = 0; i < N; i++) {Arrays.fill(g[i], 0x3f3f3f3f);g[i][i] = 0;}for (int i = 0; i < m; i++) {int a = sc.nextInt(), b = sc.nextInt(), c = sc.nextInt();g[a][b] = Math.min(g[a][b], c);}dijkstra(1, dist);if (dist[n] != 0x3f3f3f3f)System.out.println(dist[n]);elseSystem.out.println(-1);}static void dijkstra(int start, int[] dist) {Arrays.fill(dist, 0x3f3f3f3f);Arrays.fill(st, false);dist[start] = 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 j = 1; j <= n; j++)dist[j] = Math.min(dist[j], dist[t] + g[t][j]);}}}
