使用 Bellman-Ford 算法查找从源节点到目标节点的最短路径的 Golang 程序
Bellman-ford 算法用于在加权有向图中查找从源节点到其他节点的最短距离。此算法还可以预测图中的负权环。它的时间复杂度为 O(V*E),其中 V 代表顶点,E 代表边。在这篇 Golang 文章中,我们将编写程序以使用 Bellman-ford 算法查找从源节点到目标节点的最短路径。
语法
func range(variable)
range 函数迭代任何数据类型。要利用它,首先键入 range 关键字,后跟我们要迭代到的数据类型,循环将一直迭代到变量的最后一个元素。make([] 类型, 大小, 容量)
func make ([] type, size, capacity)
Go 中的 make 函数用于构建数组/映射。它接收要生成的变量的类型以及其大小和容量作为参数。
算法
步骤 1 - 创建距离数组。
步骤 2 - 重复放松边界
步骤 3 - 检查负权环。
步骤 4 - 查找最短距离。
步骤 5 - 确定最短距离。
示例
在此示例中,我们将编写一个 Go 语言程序,以借助名为 Bellman-ford 算法的最短路径查找算法,查找从源节点到目标节点的最短路径。
package main
import (
"fmt"
"math"
)
type Edge struct {
source, target, weight int
}
func Bellman_ford(edges []Edge, num_vertices, source int, target int) ([]int, error) {
distances := make([]int, num_vertices)
for i := range distances {
distances[i] = math.MaxInt32
}
distances[source] = 0
for i := 0; i < num_vertices-1; i++ {
for _, edge := range edges {
if distances[edge.source]+edge.weight < distances[edge.target] {
distances[edge.target] = distances[edge.source] + edge.weight
}
}
}
for _, edge := range edges {
if distances[edge.source]+edge.weight < distances[edge.target] {
return nil, fmt.Errorf("graph contains negative-weight cycle")
}
}
return distances, nil
}
func main() {
edges := []Edge{
{0, 1, 4},
{0, 2, 3},
{1, 3, 2},
{1, 4, 3},
{1, 2, 1},
{2, 1, 1},
{2, 3, 4},
{2, 4, 5},
{4, 3, 2},
}
num_vertices := 5
source := 0
target := 3
distances, err := Bellman_ford(edges, num_vertices, source, target)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Shortest distances from source to all vertices:")
for i, distance := range distances {
fmt.Printf("Vertex %d: %d\n", i, distance)
}
fmt.Printf("Shortest distance from source to target (vertex %d to vertex %d): %d\n", source, target, distances[target])
}
输出
Shortest distances from source to all vertices: Vertex 0: 0 Vertex 1: 4 Vertex 2: 3 Vertex 3: 6 Vertex 4: 7 Shortest distance from source to target (vertex 0 to vertex 3): 6
结论
在本文中,我们探讨了一个使用 Bellman-ford 算法查找从源顶点到目标节点的最短路径的程序。该方法简单直接,可以根据手头问题的需求随时使用。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP