Java版迪杰斯特拉算法

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class Dijkstra {
    //有向图 两个节点如果无边,用Integer.MAX_VALUE替代,
    // path初始化值皆为-1;start 表示起始点
    public void getpath(int[][] graph,int[] path,int start){
        int n=graph.length;
        if(n<2) return;
        Set<Integer> V_S=new HashSet<>();
        for(int i=0;i<n;i++) V_S.add(i);
        V_S.remove(start);

        //选择第一个候选点
        int next=-1;
        int dis=Integer.MAX_VALUE;
        for(int i:V_S){
            if(graph[start][i]<dis){
                dis=graph[start][i];
                next=i;
            }
        }
        if(next==-1) return;
        V_S.remove(next);
        path[next]=start;
      //选择剩余的n-2个候选点

        for(int i=0;i<n-2;i++){
            int candidate=next;
            int dis2=Integer.MAX_VALUE;
            for(Integer node:V_S){
                if(graph[start][next]!=Integer.MAX_VALUE
                        && graph[next][node]!=Integer.MAX_VALUE){
                    if(graph[start][next]+graph[next][node]<graph[start][node]){
                        graph[start][node]=graph[start][next]+graph[next][node];
                        path[node]=next;
                    }
                }
                if(graph[start][node]<dis2){
                    dis2=graph[start][node];
                    candidate=node;
                }

            }

            if(candidate==next) return;
            next=candidate;
            V_S.remove(next);
        }
    }

    public static void main(String[] args){
        int[][] graph={
                { Integer.MAX_VALUE,      16,     13,     Integer.MAX_VALUE,      Integer.MAX_VALUE,      Integer.MAX_VALUE, },
                {Integer.MAX_VALUE,      Integer.MAX_VALUE,      Integer.MAX_VALUE,      12,     Integer.MAX_VALUE,      Integer.MAX_VALUE,},
                {Integer.MAX_VALUE,      2,      Integer.MAX_VALUE,      Integer.MAX_VALUE,      14,     Integer.MAX_VALUE,},
                {Integer.MAX_VALUE,      Integer.MAX_VALUE,      9,      Integer.MAX_VALUE,      Integer.MAX_VALUE,      20},
                {Integer.MAX_VALUE,      Integer.MAX_VALUE,      Integer.MAX_VALUE,      7,      Integer.MAX_VALUE,      4,},
                {Integer.MAX_VALUE,      Integer.MAX_VALUE,      Integer.MAX_VALUE,      Integer.MAX_VALUE,      Integer.MAX_VALUE,      Integer.MAX_VALUE}
        };

        Dijkstra s=new Dijkstra();
        int[] path=new int[6];
        Arrays.fill(path,-1);
        s.getpath(graph,path,0);
        System.out.println(Arrays.toString(path));

        for(int i=0;i<6;i++){
            System.out.println("from "+0+" to "+i+" is "+graph[0][i]);
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值