1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| package main
import "fmt"
const( MaxDis int = 1<<7-1 )
type Dijkstra struct { tPints []string tTwoPointDis map[string]int }
func (d *Dijkstra) Init(tPoints []string, tDis [][]int) { if len(tPoints) != len(tDis) { panic("点数与矩阵的大小不一致") } d.tTwoPointDis = make(map[string]int, 0) for i := 0; i < len(tPoints); i++ { for j := 0; j < len(tPoints); j++ { key := tPoints[i] + "_" + tPoints[j] d.tTwoPointDis[key] = tDis[i][j] } } d.tPints = tPoints }
func (d *Dijkstra) dijkstra() { tPoints := d.tPints[1:] visited := []string{d.tPints[0]} src := d.tPints[0] pre, next := src, src
path := make(map[string][]string, 0) path[src + "_" + src] = []string{"A"}
distanceGraph := make(map[string]int, 0) for len(tPoints) > 0 { distance := MaxDis var ind int = 0 var dst string
var nextInd int = 0
for _, v := range visited { for ind, dst = range tPoints { newDis := d.tTwoPointDis[src + "_" + v] + d.tTwoPointDis[v + "_" + dst] if newDis < distance { distance = newDis pre = v next = dst nextInd = ind d.tTwoPointDis[src + "_" + dst] = distance } } }
for _, tPoint := range path[src + "_" + pre] { path[src + "_" + next] = append(path[src + "_" + next], tPoint) } path[src + "_" + next] = append(path[src + "_" + next], next)
distanceGraph[src + "_" + next] = distance
visited = append(visited, next) tPoints = append(tPoints[:nextInd], tPoints[nextInd+1:]...) }
fmt.Println(path) fmt.Println(distanceGraph) }
func main() { d := new(Dijkstra) tPoints := []string{"A", "B", "C", "D"} tDis := [][]int{ {0, 2, 6, 4}, {127, 0, 3, 127}, {7, 127, 0, 1}, {5, 127, 12, 0}}
d.Init(tPoints, tDis) d.dijkstra() }
|