[算法]Dijkstra算法模板(java)

注: 稠密图用邻接矩阵存储 稀疏图用邻接表

时间复杂度o(n2)



import java.util.Scanner;

public class Main {
	
	static int n,m;
	static int N = 510;
	//邻接矩阵来存储图
	static int [][] g = new int[N][N];
	//已经求出最短路点的集合
	static boolean [] visited = new boolean[N];
	//起点到第i个点最短距离
	static int [] dist = new int[N];
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String [] s = in.nextLine().split(" ");
		n = Integer.parseInt(s[0]); m = Integer.parseInt(s[1]);
		//初始化邻接矩阵
		for(int i=1;i<=n;i++){
			for(int j=1;j<=n;j++){
				if(i==j) g[i][j] = 0;
				else g[i][j] = Integer.MAX_VALUE;
			}
		}
		
		for(int i=0;idist[j])){
					t = j;
				}
			}
			visited[t] = true;
			//拓展
			for(int j=1;j<=n;j++){
				if(g[t][j]!= Integer.MAX_VALUE)
					dist[j] = Math.min(dist[j], dist[t]+g[t][j]);
			}
		}
		if(dist[n] == Integer.MAX_VALUE) System.out.println(-1);
		
		else System.out.println(dist[n]);
 		
	}
}

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