最短路徑:
對於網圖來說,最短路徑是指兩個頂點之間經過的邊上權值和最少的路徑,我們稱第一個頂點是源點,最后一個頂點是終點
迪傑斯特拉 ( Dijkstra) 算法是並不是一下子就求出 了 Vo 到V8 的最短路徑,而是一步步求出它們之間頂點的最短路徑,過程中都是基於已經求出的最短路徑的基礎上,求得更遠頂點的最短路徑,最終得到你要的結果
JS代碼:
//定義鄰接矩陣 let Arr2 = [ [0, 1, 5, 65535, 65535, 65535, 65535, 65535, 65535], [1, 0, 3, 7, 5, 65535, 65535, 65535, 65535], [5, 3, 0, 65535, 1, 7, 65535, 65535, 65535], [65535, 7, 65535, 0, 2, 65535, 3, 65535, 65535], [65535, 5, 1, 2, 0, 3, 6, 9, 65535], [65535, 65535, 7, 65535, 3, 0, 65535, 5, 65535], [65535, 65535, 65535, 3, 6, 65535, 0, 2, 7], [65535, 65535, 65535, 65535, 9, 5, 2, 0, 4], [65535, 65535, 65535, 65535, 65535, 65535, 7, 4, 0], ] let numVertexes = 9, //定義頂點數 numEdges = 15; //定義邊數 // 定義圖結構 function MGraph() { this.vexs = []; //頂點表 this.arc = []; // 鄰接矩陣,可看作邊表 this.numVertexes = null; //圖中當前的頂點數 this.numEdges = null; //圖中當前的邊數 } let G = new MGraph(); //創建圖使用 //創建圖 function createMGraph() { G.numVertexes = numVertexes; //設置頂點數 G.numEdges = numEdges; //設置邊數 //錄入頂點信息 for (let i = 0; i < G.numVertexes; i++) { G.vexs[i] = 'V' + i; //scanf('%s'); //ascii碼轉字符 //String.fromCharCode(i + 65); } console.log(G.vexs) //打印頂點 //鄰接矩陣初始化 for (let i = 0; i < G.numVertexes; i++) { G.arc[i] = []; for (j = 0; j < G.numVertexes; j++) { G.arc[i][j] = Arr2[i][j]; //INFINITY; } } console.log(G.arc); //打印鄰接矩陣 } let Pathmatirx = [] // 用於存儲最短路徑下標的數組,下標為各個頂點,值為下標頂點的前驅頂點 let ShortPathTable = [] //用於存儲到各點最短路徑的權值和 function Dijkstra() { let k, min; let final = []; for (let v = 0; v < G.numVertexes; v++) { final[v] = 0; ShortPathTable[v] = G.arc[0][v]; Pathmatirx[v] = 0; } ShortPathTable[0] = 0; final[0] = 1; for (let v = 1; v < G.numVertexes; v++) { //初始化數據 min = 65535; for (let w = 0; w < G.numVertexes; w++) { //尋找離V0最近的頂點 if (!final[w] && ShortPathTable[w] < min) { k = w; min = ShortPathTable[w]; //w 頂點離V0頂點更近 } } final[k] = 1; //將目前找到的最近的頂點置位1 for (let w = 0; w < G.numVertexes; w++) { //修正當前最短路徑及距離 if (!final[w] && (min + G.arc[k][w] < ShortPathTable[w])) { //說明找到了更短的路徑,修改Pathmatirx[w]和ShortPathTable[w] ShortPathTable[w] = min + G.arc[k][w]; Pathmatirx[w] = k; } } } } function PrintVn(Vn) { //打印V0-Vn最短路徑 console.log("%s-%s 最小權值和: %d", G.vexs[0], G.vexs[Vn], ShortPathTable[Vn]); //打印最短路線 let temp = Vn, str = ''; while (temp != 0) { str = '->' + G.vexs[temp] + str temp = Pathmatirx[temp] } str = 'V0' + str; console.log('最短路線:'+str); } createMGraph(); Dijkstra(); PrintVn(8);
運行結果:
迪傑斯特拉 ( Dijkstra) 算法是 一個按路徑長度遞增的次序產生最短路徑的算法。時間復雜度為 O(n2),n為頂點個數,如果是從其他頂點開始,那么在原有算法的基礎上再來一次循環,此時的時間復雜度為O(n3)。