Dijkstra
java源码
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Vertex{
Vertex(int id ,int value){
this.id=id;
this.value=value;
}
int id;
int value;
}
public class Dijkstra {
static int []visited;
static int []distance;
static int []parent;
public static void main(String[] args) {
ArrayList <Vertex> al[]=new ArrayList[6];
for(int i=0;i<al.length ;i++){
al[i]=new ArrayList<Vertex>();
}
//构建图
al[0].add(new Vertex(1,8));
al[0].add(new Vertex(2,2));
al[0].add(new Vertex(3,6));
al[1].add(new Vertex(0,8));
al[1].add(new Vertex(2,4));
al[1].add(new Vertex(4,4));
al[2].add(new Vertex(0,2));
al[2].add(new Vertex(1,4));
al[2].add(new Vertex(3,5));
al[2].add(new Vertex(4,9));
al[2].add(new Vertex(5,6));
al[3].add(new Vertex(0,6));
al[3].add(new Vertex(2,5));
al[3].add(new Vertex(5,3));
al[4].add(new Vertex(1,4));
al[4].add(new Vertex(2,9));
al[4].add(new Vertex(5,1));
al[5].add(new Vertex(2,6));
al[5].add(new Vertex(3,3));
al[5].add(new Vertex(4,1));
parent=new int[6];
distance=new int[6];
for(int i=0;i<distance.length;i++){
distance[i]=Integer.MAX_VALUE;
}
DijkStra(al,0);
}
static void DijkStra(ArrayList<Vertex> []al,int s){
//初始节点入队
Map<Integer,Integer>map=new HashMap<Integer,Integer>();
map.put(0, s);
//设置初始节点的相关属性
distance[s]=0;
parent[s]=-1;
while(map.size()>0){
//将队列排序
List<Map.Entry<Integer,Integer>>l=new ArrayList<Map.Entry<Integer,Integer>>(map.entrySet());
Collections.sort(l, new Comparator<Map.Entry<Integer,Integer>>(){
@Override
public int compare(Map.Entry<Integer,Integer>o1,Map.Entry<Integer,Integer>o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
//将队列中最小距离的根节点取出,并设置已访问。
int vertex=l.get(0).getKey();
map.remove(l.get(0).getKey());
for(int i=0;i<al[vertex].size();i++){
//获得叶子节点的id 和 距离
int node=al[vertex].get(i).id;
int distance2=al[vertex].get(i).value;
//判断当前距离是否最小(或者说是比上次的小),然后更新
int distance12=distance[vertex]+distance2;
if(distance12<distance[node]){
map.put(node,distance12);
parent[node]=vertex;
distance[node]=distance12;
}
}
//打印信息
System.out.println("当前父节点为 :"+vertex);
System.out.println("parent对应值为:");
for(int t:parent)System.out.print(t+" ");
System.out.println();
System.out.println("到各点距离为:");
for(int t:distance)System.out.print(t+" ");
System.out.println();
System.out.println("------------------------------");
}
}
}
运行结果:
当前父节点为 :0
parent对应值为:
-1 0 0 0 0 0
到各点距离为:
0 8 2 6 2147483647 2147483647
当前父节点为 :2
parent对应值为:
-1 2 0 0 2 2
到各点距离为:
0 6 2 6 11 8
当前父节点为 :1
parent对应值为:
-1 2 0 0 1 2
到各点距离为:
0 6 2 6 10 8
当前父节点为 :3
parent对应值为:
-1 2 0 0 1 2
到各点距离为:
0 6 2 6 10 8
当前父节点为 :5
parent对应值为:
-1 2 0 0 5 2
到各点距离为:
0 6 2 6 9 8
当前父节点为 :4
parent对应值为:
-1 2 0 0 5 2
到各点距离为:
0 6 2 6 9 8