Dijkstra 算法实例(go代码)

如图所示,求节点a到各节点的最段路径

Dijkstra 算法实例(go代码)_第1张图片

代码如下

package main

import "fmt"

const (
	MAX_INT = int(^uint(0) >> 1)
)

func main() {
	var graph = [][]int{
		{0, 10, MAX_INT, 30, 100},
		{MAX_INT, 0, 50, MAX_INT, MAX_INT},
		{MAX_INT, MAX_INT, 0, MAX_INT, 10},
		{MAX_INT, MAX_INT, 20, 0, 60},
		{MAX_INT, MAX_INT, MAX_INT, MAX_INT, 0},
	}
	fmt.Printf("%v\n", Dijkstra(graph, 0))
}

func Dijkstra(graph [][]int, start int) []int {
	nodeNum := len(graph)
	if nodeNum == 0 {
		return nil
	}
	cost := make([]int, 0, nodeNum)
	cost = append(cost, graph[start]...) // 记录在当前节点位置时,最短路径,从start节点开始
	flag := make([]bool, nodeNum)        // 记录节点是否访问过
	flag[start] = true

	for k := 0; k < nodeNum; k++ {
		min := MAX_INT
		idx := 0
		for i := range cost { // 找到当前未访问的节点中的最短路径的节点
			if !flag[i] && cost[i] < min {
				min = cost[i]
				idx = i
			}
		}
		flag[idx] = true      // 标记节点已访问
		for i := range cost { // 以idx节点为当前节点,更新最短路径
			if !flag[i] && graph[idx][i] != MAX_INT && cost[idx] != MAX_INT && cost[i] > graph[idx][i]+cost[idx] {
				cost[i] = graph[idx][i] + cost[idx]
			}
		}
	}

	return cost
}
  • 输出
[0 10 50 30 60]

你可能感兴趣的:(笔记,算法,golang,开发语言)