最短路——Dijkstra

Dijkstra

最短路——Dijkstra_第1张图片

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  al[]=new ArrayList[6];
		for(int i=0;i();
		}
		//构建图
		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 []al,int s){
		//初始节点入队
		Mapmap=new HashMap();
		map.put(0, s);
		//设置初始节点的相关属性
		distance[s]=0;
		parent[s]=-1;
		while(map.size()>0){
			//将队列排序
			List>l=new ArrayList>(map.entrySet());
			Collections.sort(l, new Comparator>(){
				@Override
				public int compare(Map.Entryo1,Map.Entryo2) {
					return (o1.getValue()).compareTo(o2.getValue());
				}
			});
			//将队列中最小距离的根节点取出,并设置已访问。
			int vertex=l.get(0).getKey();
			map.remove(l.get(0).getKey());
			for(int i=0;i

运行结果:

当前父节点为 :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

你可能感兴趣的:(算法)