Dijkstra求最短路 Java实现

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();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值