Golang 使用Bellman-Ford算法,从源节点到目标节点找到最短路径

Golang 使用Bellman-Ford算法,从源节点到目标节点找到最短路径

Bellman-Ford算法用于在加权有向图中找到从源节点到其他节点的最短距离。该算法还可以预测图中的负权重循环。它的时间复杂度为O(V*E),其中V表示顶点,E表示边。在这篇Golang文章中,我们将编写程序,使用Bellman-Ford算法找到从源节点到目标节点的最短路径。

语法

func range(variable)

range函数可以迭代任何数据类型。要使用它,首先键入range关键字,然后后面跟上要迭代的数据类型,循环会一直迭代直到达到变量的最后一个元素。 make([]kind, size, and capacity)

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算法找到从源顶点到目标节点的最短路径的程序。这种方法简单直观,可以根据手头问题的需求随时使用。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程