這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
//假設有9個節點,圖在代碼下方,可以參考
shortTablePath存放著V0到Vx某節點的最短路徑
該演算法,第一次先將V0的節點串連的權值存入shortTablePath,沒串連的,用MAXWEIGHT表示.
package mainimport ("fmt")const MAXVEX int = 9const MAXWEIGHT int = 1000var shortTablePath = [MAXVEX]int{MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT}func main() {graph := NewGraph()var TablePathMin int //存放shortTablePath中,未遍曆的最小結點的值var Vx int //存放shortTablePath中,未遍曆的最小結點的下標var isgetPath [MAXVEX]bool //記錄結點是否已經找到v0到vx的最小路徑// 擷取v0這一行的權值數組for v := 0; v < len(graph); v++ {shortTablePath[v] = graph[0][v]}shortTablePath[0] = 0isgetPath[0] = true//遍曆v1 ~ v8for v := 1; v < len(graph); v++ {TablePathMin = MAXWEIGHT//找出shortTablePath中,未遍曆的最小結點的值for w := 0; w < len(graph); w++ {if !isgetPath[w] && shortTablePath[w] < TablePathMin {Vx = wTablePathMin = shortTablePath[w]}}isgetPath[Vx] = truefor j := 0; j < len(graph); j++ {if !isgetPath[j] && TablePathMin+graph[Vx][j] < shortTablePath[j] {shortTablePath[j] = TablePathMin + graph[Vx][j]}}fmt.Println("遍曆完V", v, "後:", shortTablePath)}//輸出for i := 0; i < len(shortTablePath); i++ {fmt.Println("V0到V", i, "最小路徑:", shortTablePath[i])}}func NewGraph() [MAXVEX][MAXVEX]int {var graph [MAXVEX][MAXVEX]intvar v0 = [MAXVEX]int{0, 1, 5, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT}var v1 = [MAXVEX]int{1, 0, 3, 7, 5, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT}var v2 = [MAXVEX]int{5, 3, 0, MAXWEIGHT, 1, 7, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT}var v3 = [MAXVEX]int{MAXWEIGHT, 7, MAXWEIGHT, 0, 2, MAXWEIGHT, 3, MAXWEIGHT, MAXWEIGHT}var v4 = [MAXVEX]int{MAXWEIGHT, 5, 1, 2, 0, 3, 6, 9, MAXWEIGHT}var v5 = [MAXVEX]int{MAXWEIGHT, MAXWEIGHT, 7, MAXWEIGHT, 3, 0, MAXWEIGHT, 5, MAXWEIGHT}var v6 = [MAXVEX]int{MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, 3, 6, MAXWEIGHT, 0, 2, 7}var v7 = [MAXVEX]int{MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, 9, 5, 2, 0, 4}var v8 = [MAXVEX]int{MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, MAXWEIGHT, 7, 4, 0}graph[0] = v0graph[1] = v1graph[2] = v2graph[3] = v3graph[4] = v4graph[5] = v5graph[6] = v6graph[7] = v7graph[8] = v8return graph}
graph 圖:
遍曆完V 1 後: [0 1 4 8 6 1000 1000 1000 1000]
遍曆完V 2 後: [0 1 4 8 5 11 1000 1000 1000]
遍曆完V 3 後: [0 1 4 7 5 8 11 14 1000]
遍曆完V 4 後: [0 1 4 7 5 8 10 14 1000]
遍曆完V 5 後: [0 1 4 7 5 8 10 13 1000]
遍曆完V 6 後: [0 1 4 7 5 8 10 12 17]
遍曆完V 7 後: [0 1 4 7 5 8 10 12 16]
遍曆完V 8 後: [0 1 4 7 5 8 10 12 16]
V0到V 0 最小路徑: 0
V0到V 1 最小路徑: 1
V0到V 2 最小路徑: 4
V0到V 3 最小路徑: 7
V0到V 4 最小路徑: 5
V0到V 5 最小路徑: 8
V0到V 6 最小路徑: 10
V0到V 7 最小路徑: 12
V0到V 8 最小路徑: 16