Dijkstra求最短路
OJ链接 :
题目描述:
一个 n 个点 m 条边的有向图,图中可能存在重边和自环,所有边权均为非负值。
请你求出 1 号点到 n 号点的最短距离,如果无法从 1 号点走到 n 号点,则输出 −1。
输入格式
第一行包含整数 n 和 m。
接下来 m 行每行包含三个整数 x,y,z,表示存在一条从点 x 到点 y 的有向边,边长为 z。
输出格式
输出一个整数,表示 1 号点到 n 号点的最短距离。
如果路径不存在,则输出 −1。
数据范围
1≤n<500 ,m≤×10^5
图中涉及边长均不小于 00,且不超过 10000。
样例输入输出:
Simple Input
3 3
1 2 2
2 3 1
1 3 4
Simple Output
3
题目分析:
- 属于最短路问题
- 属于无负边权的稀疏图
- 使用朴素Dijkstra
题目代码:
import java.io.*;
import java.util.*;
public class 朴素Dijkstra{
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
static final int N = 505;
static int w[][] = new int[N][N];
static int dis[] = new int[N]; // 每个点距离原点的距离。
static int S[] = new int[N]; // 最短路集合
static int n,m;
public static int Int(String s){
return Integer.parseInt(s);
}
public static int Dijkstra(){
Arrays.fill(dis, 0x3f3f3f3f);
dis[1] = 0;
for(int i = 0; i < n; i++){ // 循环n次, 每次找出一个离起点最近的点。
int t = -1;
for(int j = 1; j <= n; j++){
if(S[j] == 0 && (t == -1 || dis[t] > dis[j])){ // 找到一个距离最短的加入S集合。
t = j;
}
}
S[t] = 1; // 然后通过这个点来缩短原点到达其他点的距离。
for(int j = 2; j <= n; j++){
dis[j] = Math.min(dis[j], dis[t] + w[t][j]);
}
}
if(dis[n] != 0x3f3f3f3f) return dis[n];
else return -1;
}
public static void main(String[] args) throws Exception{
String s[] = in.readLine().split(" ");
n = Integer.parseInt(s[0]);
m = Integer.parseInt(s[1]);
for(int i = 0; i < n; i++)
Arrays.fill(w[i], 0x3f3f3f3f);
for(int i = 0; i < m; i++){
String s1[] = in.readLine().split(" ");
int a, b, c;
a = Int(s1[0]);
b = Int(s1[1]);
c = Int(s1[2]);
w[a][b] = Math.min(w[a][b],c);
}
out.write(Dijkstra()+"\n");
out.flush();
}
}