package main
import (
"fmt"
"math"
)
type Edge struct {
from, to, weight int
}
func bellmanFord(edges []Edge, vertices int, start int) ([]int, bool) {
dist := make([]int, vertices)
for i := range dist {
dist[i] = math.MaxInt32
}
dist[start] = 0
// Relax edges repeatedly
for i := 0; i < vertices-1; i++ {
updated := false
for _, e := range edges {
if dist[e.from] != math.MaxInt32 && dist[e.from]+e.weight < dist[e.to] {
dist[e.to] = dist[e.from] + e.weight
updated = true
}
}
if !updated {
break
}
}
// Check for negative weight cycles
for _, e := range edges {
if dist[e.from] != math.MaxInt32 && dist[e.from]+e.weight < dist[e.to] {
return dist, false // Negative cycle detected
}
}
return dist, true
}
func main() {
// Vertices: A=0, B=1, C=2
edges := []Edge{
{0, 1, 5},
{0, 2, -3},
{1, 2, 2},
}
dist, ok := bellmanFord(edges, 3, 0)
if !ok {
fmt.Println("Graph contains a negative weight cycle")
return
}
for i, d := range dist {
fmt.Printf("Distance from A to %c: %d\n", 'A'+i, d)
}
}
Set distance to start vertex as zero
for i := 0; i < vertices-1; i++ {
Repeat relaxation for all vertices minus one times
if dist[e.from] != math.MaxInt32 && dist[e.from]+e.weight < dist[e.to] {
Check if current edge can improve distance to destination
dist[e.to] = dist[e.from] + e.weight
Update distance to destination vertex
Stop early if no updates in this iteration
for _, e := range edges { if dist[e.from] != math.MaxInt32 && dist[e.from]+e.weight < dist[e.to] { return dist, false } }
Detect negative weight cycle by checking for further improvements
Distance from A to A: 0
Distance from A to B: 5
Distance from A to C: -3