最短路徑Dijkstra (JAVA實現)

代碼有註釋:

public class Dijkstra {

	static int[][] map;// 存圖
	static int[] vis; // 看當前點是否走過,走過 1 ,未0
	static int[] dis; // 存儲起點到 其他各點的距離
	static int m, n;// 圖中的 點 與 線
	static int Max = 0x3f3f3f; // 定義如果兩個點不連通的最大值

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		m = sc.nextInt();// 點
		n = sc.nextInt();// 線
		map = new int[m + 1][m + 1];
		vis = new int[m + 1];
		dis = new int[m + 1];
		for (int i = 0; i < m+1; i++) {
			for (int j = 0; j < m+1; j++) {
				map[i][j] =Max;
			}
			
		}
		for (int i = 0; i < n; i++) {
			int a, b, s; // a點到 b點的距離爲 s
			a = sc.nextInt();
			b = sc.nextInt();
			s = sc.nextInt();
			if (s < map[a][b]) // 防止有重邊
				map[a][b] = map[b][a] = s;// 假定圖的連接時雙向的
		}
		
		
		dijkstra(1);// 傳入參數,起點
		System.out.println("起點到各個點的最短距離是:");
		for (int i = 1; i <= m; i++) {
			System.out.println(dis[i]);
		}
	}

	private static void dijkstra(int start) {
		// 將vis數組初始化 0
		Arrays.fill(vis, Max);
		// 初始化 dis 數組
		for (int i = 1; i <= m; i++) {
			dis[i] = map[start][i];
		}
		// 起點到起點的距離 爲 0
		dis[start] = 0;
		// 起點已經走過
		vis[start] = 1;

		int min, pos;// min 當前的最小距離,pos 當前點
		pos = 1;
		for (int i = 1; i < m; i++) {
			min = Max;
			for (int j = 1; j <= m; j++) {
				if (vis[j] != 1 && dis[j] < min) {//找到當前到J點的最短路
					min = dis[j];
					pos = j;
				}
			}
			vis[pos] = 1;// pos當前點已經走過
			for (int j = 1; j <= m; j++) {
				// 以當前點 pos 爲中間點,更新dis距離
				if (vis[j] != 1 && dis[j] > dis[pos] + map[pos][j]) {
					dis[j] = dis[pos] + map[pos][j];
				}
			}
		}
	}

}
        /*
             3 2
             1 2 1
             2 3 1
             起點到各個點的最短距離是:
             0
             1
             2
        */

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章