码迷,mamicode.com
首页 > 编程语言 > 详细

迪杰斯特拉算法实现

时间:2019-05-28 14:17:02      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:class   lse   ndis   static   ati   node   find   bool   style   

public class Dijkstra 
{//节点为A,B,C,D,E,F  以二维数组graph表示连通图
    private static int N = 1000;
    private static int[][] Graph = {
            { 0,-1,3,N,N},
            { N,0,3,2,2 },
            { N,N,0,N,N },
            { N,1,5,0,N },
            { N,N,N,-3,0},
    };
    
    
    public static void dijkstra(int vs, int[][] Graph)
    {
        int NUM = Graph[0].length;
//        System.out.println(NUM);
        int[] prenode = new int[NUM];
        int[] mindist = new int[NUM];
        boolean[] find = new boolean[NUM];
        
        int vnear = 0;
        
        for(int i = 0; i < mindist.length; i++)
        {
            prenode[i] = i;
            mindist[i] = Graph[vs][i];
            find[i] = false;
        }
        
        find[vs] = true;
        
//        System.out.println(Graph.length);        
        for(int v = 1; v < Graph.length; v++)
        {
            int min = N;
            for(int j = 0; j < Graph.length; j++)
            {
                if(!find[j] && mindist[j] < min)
                {
                    min = mindist[j];
                    vnear = j;
                }
            }
            find[vnear] = true;
            
            
            for(int k = 0; k < Graph.length; k++)
            {
                if(!find[k] && (min + Graph[vnear][k]) < mindist[k])
                {
                    prenode[k] = vnear;
                    mindist[k] = min + Graph[vnear][k];
                }
            }            
        }
        int t = ‘A‘;
        for(int i = 0; i < NUM; i++)
            System.out.println("A" + "::"+(char)(t+prenode[i]) + "->" +(char)(t+i) + ", s=" + mindist[i]);
            //System.out.println("v" + vs + "...v" + prenode[i] + "->v" + i + ", s=" + mindist[i]);
    }
    public static void main(String[] args)
    {
        dijkstra(0, Graph);
    }

}

 

迪杰斯特拉算法实现

标签:class   lse   ndis   static   ati   node   find   bool   style   

原文地址:https://www.cnblogs.com/womendouyiyang/p/10936904.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!