使用 Dijkstra 算法查找图中所有节点对之间最短路径的 Golang 程序


在这篇 Golang 程序文章中,我们将学习如何使用结构体 Edge 来表示图中的加权边,以及 dijkstra 函数如何接收节点数 n 和 Edge 对象切片作为输入。它返回一个二维切片,表示图中所有节点对之间的距离矩阵。

在这篇 Golang 文章中,我们将探讨如何在图中实现 Dijkstra 算法以查找所有节点对之间的最短路径。

算法

  • 步骤 1 − 首先,我们需要导入 fmt 和 math 包。然后定义一个 Edge 结构体来表示图中的加权边,其字段包括起始节点、结束节点和边权重。

  • 步骤 2 − 定义一个函数 dijkstra(n int, edges []Edge) [][]int,该函数接收节点数 n 和 Edge 对象切片作为输入,并返回一个二维切片,表示图中所有节点对之间的距离矩阵。

  • 步骤 3 − 初始化一个大小为 n x n 的邻接矩阵 adj,并将所有条目设置为无穷大,除了对角线条目,这些条目设置为 0。根据输入切片中的边填充邻接矩阵。

  • 步骤 4 − 初始化一个大小为 n x n 的距离矩阵 dist,并将邻接矩阵中的值复制到其中。

  • 步骤 5 − 使用三个嵌套循环计算所有节点对之间的最短路径。外循环遍历所有节点 k,内循环遍历所有节点对 i 和 j。

  • 步骤 6 − 对于每一对节点,检查从 i 到 k 的距离加上从 k 到 j 的距离是否小于从 i 到 j 的当前距离。如果是,则使用新的最短路径距离更新距离矩阵,并返回距离矩阵。

  • 步骤 7 − 现在,开始 main() 函数。在 main() 中,通过将图的边作为值传递给它来初始化一个数组。

  • 步骤 8 − 然后调用 dijkastra() 函数,并将上面初始化的数组作为参数传递给该函数,并将获得的结果存储在一个变量中。

  • 步骤 9 − 最后打印获得的结果,即图中所有节点对之间的最短路径。

示例

以下示例表示图中所有节点对之间的距离矩阵,其中 dist[i][j] 表示从节点 i 到节点 j 的最短路径距离。例如,dist[0][1] 为 5,这意味着从节点 0 到节点 1 的最短路径权重为 5。类似地,dist[2][3] 为 1,这意味着从节点 2 到节点 3 的最短路径权重为 1。

package main

import (
   "fmt"
   "math"
)

type Edge struct {
   from int
   to   int
   cost int
}

func dijkstra(n int, edges []Edge) [][]int {
   // Initialize adjacency matrix
   adj := make([][]int, n)
   for i := 0; i < n; i++ {
      adj[i] = make([]int, n)
      for j := 0; j < n; j++ {
         if i == j {
            adj[i][j] = 0
         } else {
            adj[i][j] = math.MaxInt32
         }
      }
   }

   // Build adjacency matrix
   for _, e := range edges {
      adj[e.from][e.to] = e.cost
   }

   // Initialize distance matrix
   dist := make([][]int, n)
   for i := 0; i < n; i++ {
      dist[i] = make([]int, n)
      copy(dist[i], adj[i])
   }

   // Compute shortest path between all pairs
   for k := 0; k < n; k++ {
      for i := 0; i < n; i++ {
         for j := 0; j < n; j++ {
            if dist[i][k]+dist[k][j] < dist[i][j] {
               dist[i][j] = dist[i][k] + dist[k][j]
            }
         }
      }
   }
   return dist
}

func main() {
   n := 4
   edges := []Edge{
      {0, 1, 5},
      {0, 2, 10},
      {1, 2, 3},
      {2, 3, 1},
      {3, 0, 2},
   }
   fmt.Println("The given vertices of graph are:", edges)
   dist := dijkstra(n, edges)
   fmt.Println("The shortest distance between all pairs of nodes are:", dist)
}

输出

The given vertices of graph are: [{0 1 5} {0 2 10} {1 2 3} {2 3 1} {3 0 2}]
The shortest distance between all pairs of nodes are: [[0 5 8 9] [6 0 3 4] [3 8 0 1] [2 7 10 0]]

结论

我们已经成功编译并执行了一个 Go 语言程序,使用 Dijkstra 算法查找图中所有节点对之间的最短路径。Dijkstra 算法是计算图中最短路径的强大工具,本文中提供的 Go 实现提供了一种清晰简单的方法来应用该算法以查找图中所有节点对之间的最短路径。

更新于: 2023年4月5日

477 次查看

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.