图论记录之最短路迪杰斯特拉

简述思想

这个思想能用一句话来概括,精简到的极致:每次找到一个最短距离的点并更新起点到各个点的最短距离

如果要可视化的化,B站搜索Dijksra算法,有视频讲解

代码

这里是Acwing的851题,下面的有注释

java 复制代码
import java.util.*;

public class Main
{
    private static int N =510;
    private static int n,m;
    private static int[] dist;//存放起点到每个点的最短距离
    private static int[][] g;//邻接矩阵
    private static boolean[] st;//若为true表示已经确定了起点到i点的最短距离
    static Scanner in = new Scanner(System.in);
    static int dijkstra()
    {
       Arrays.fill(dist,100001);
       dist[1]=0;//从起点到起点是0,这个很好理解
       // 迭代n次
       for(int i=0;i<n;i++){
           int t=-1;
           for(int j=1;j<=n;j++){
           		/*
				!st[j]表明j这个点我还没有访问
				t==-1 表明还在初始状态,初始状态必定进入该if分支
				dist[j]<dist[t]我找到了一个比上一次的结果的距离更短的一个点
				*/
               if(!st[j] &&(t==-1 || dist[j]<dist[t]))
                t=j;
           }
           st[t]=true;//标记节点t为访问状态
           for(int j=1;j<=n;j++)
           // 1~t t->j 即先到t,再加上t到j这一段距离,也叫做最后一段距离
            dist[j]=Math.min(dist[j],dist[t]+g[t][j]);
       }
       // 能进入该分支,表明再迭代n次后,没有任何一个点能到达终点n,所以终点不可达,那么返回-1(题目要求的)
       if(dist[n]==100001)
            return -1;
        return dist[n];
    }

    public static void main(String[] args)
    {

        n = in.nextInt();
        m = in.nextInt();
        g = new int[n+1][n+1];
        dist = new int[n+1];
        st=new boolean[n+1];
        for(int[] arr:g)
            //不要写成Integer.MAX_VALUE,由于dist[t]+g[t][j],这个运算操作会溢出
            Arrays.fill(arr,100001);
        while(m-->0){
            int x = in.nextInt();
            int y = in.nextInt();
            int z = in.nextInt();
            //重复边取最小
            g[x][y] = Math.min(g[x][y],z);
        }
        System.out.println(dijkstra());
    }

}
相关推荐
莫逸风1 小时前
【AgentScope 2.0】 0. 学习指南
java·llm·agent·agentscope
从零开始的代码生活_1 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法
云小逸1 小时前
【C++ 第七阶段:模板、泛型编程与工程综合详解】
开发语言·c++
z123456789862 小时前
2026最新两款AI编程工具深度对比实测
java·数据库·ai编程
GIS阵地2 小时前
QgsSingleBandPseudoColorRenderer 完整详解(QGIS 3.40.13 C++)
开发语言·前端·c++·qt·qgis
yaoxin5211232 小时前
470. Java 反射 - Member 接口与 AccessFlag
java·开发语言·python
groundhappy3 小时前
idalib安装和codex ida-mcp配置
linux·开发语言·python
做个文艺程序员3 小时前
Linux第24篇:Java应用监控体系搭建:Prometheus+Grafana可视化运维
java·grafana·prometheus
小钻风33663 小时前
Spring Boot 文件上传详解:深入理解 MultipartFile 的使用与原理
java·开发语言
其美杰布-富贵-李3 小时前
Spring Boot 工程开发全流程说明
java·spring boot·后端