SW练习_求最短距离_迪杰斯特拉

本文介绍了迪杰斯特拉算法的概要,即从没访问的点中找到离起点最近的点并更新其相邻未访问点的距离。文章提出疑问,在某些情况下,如某个顶点与其他点不连接时,算法如何继续执行,并讨论了如何更新路径长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

算法概要:从没有访问的点里,找到距离起点最近的点,然后更新该点到其相邻且未访问点的距离

1.找出距离最小的点s1 这块我其实有个疑问,如果be这个顶点和别的点都不连接,那么这块计算不下去了?

2.根据s1到它连接的每一个e1,如果 (开始节点->s1)+(s1->e1)<(开始节点->e1) 那么开始节点->e1需要更新一下

package info.frady.algo;

/**
 meng3.wei 2020.04.25
 //参考 https://www.jianshu.com/p/ff6db00ad866
 从0出发到0的最短距离为:0
 0-->0
 从0出发到1的最短距离为:3
 0-->3-->1
 从0出发到2的最短距离为:3
 0-->3-->2
 从0出发到3的最短距离为:2
 0-->3
 从0出发到4的最短距离为:6
 0-->3-->2-->4
 */
public class 迪杰斯特拉 {
    public static final int M = 1000000; // 代表正无穷
    public static int n;//顶点的个数
    public static int[] shortPathLen ; // 保存start到其他各点的最短路径
    public static boolean [] visited;
    public static int[] pid;

    public static void main(String[] args) {
        // 二维数组每一行分别是 A、B、C、D、E 各点到其余点的距离,
        // A -> A 距离为0, 常量M 为正无穷
        int[][] weight1 = {
                {0,4,M,2,M},
                {4,0,4,1,M},
                {M,4,0,1,3},
                {2,1,1,0,7},
                {M,M,3,7,0}
        };
        n=weight1.length;
        pid=new int[n];
        visited=new boolean[n];
        shortPathLen=new int[n];
        int be=0;

        proceeDS(weight1,be);

        for (int i = 0; i < n; i++) {
            System.out.println("从" + 0 + "出发到" + i + "的最短距离为:" + shortPathLen[i]);
            int p=pid[i];
            StringBuffer sb=new StringBuffer();
            sb.append(i);
            while(p!=be){
                sb.append(">--"+p);
                p=pid[p];
            }
            sb.append(">--"+be);
            System.out.println(sb.reverse());
        }

    }
    public static void proceeDS(int[][] weight1,int be){//be代表起点
        pid[be]=be;
        visited[be]=true;
        shortPathLen[be]=0;

        for (int i = 1; i < n; i++) {
            int minLen=Integer.MAX_VALUE;
            int s1=0;
            for (int end = 0; end <n ; end++) {//1.找出距离最小的点s1    这块我其实有个疑问,如果be这个顶点和别的点都不连接,那么这块计算不下去了?
                if(!visited[end]  && weight1[be][end]<minLen ){
                    s1=end;
                    minLen=weight1[be][end];
                }
            }
            shortPathLen[s1]=minLen;
            visited[s1]=true;

            for (int e1 = 0; e1<n ; e1++) {//2.根据s1到它连接的每一个e1,如果 (开始节点->s1)+(s1->e1)<(开始节点->e1) 那么开始节点->e1需要更新一下
                if( !visited[e1] && (weight1[be][s1]+ weight1[s1][e1] <weight1[be][e1]) ){

                    weight1[be][e1]=weight1[be][s1]+ weight1[s1][e1];
                    pid[e1]=s1;

                }
            }
        }

    }


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值