package main import "fmt" func bellmanFord(edges [][]int, V, src int) []int { dist := make([]int, V) for i := range dist { dist[i] = 1 << 30 } dist[src] = 0 for i := 0; i < V-1; i++ { for _, edge := range edges { u, v, w := edge[0], edge[1], edge[2] if dist[u] != 1<<30 && dist[u]+w < dist[v] { dist[v] = dist[u] + w } } } return dist } func main() { edges := [][]int{ {0, 1, 4}, {0, 2, 5}, {1, 2, -3}, {2, 3, 4}, {3, 1, -6}, } dist := bellmanFord(edges, 4, 0) fmt.Println(dist) }
The Bellman-Ford algorithm relaxes edges V-1 times. Negative edges reduce distances step by step. After all relaxations, the shortest distances from source 0 are [0, 1, -2, 2].
Bellman-Ford runs V-1 iterations to relax edges. If any edge can still be relaxed after that, it means a cycle reduces distances indefinitely, indicating a negative weight cycle.
dist := make([]int, V) for i := 0; i <= V; i++ { dist[i] = 1 << 30 } dist[src] = 0
The loop runs from 0 to V inclusive, but the slice has length V, so index V is out of range causing runtime panic.
edges := [][]int{ {0, 1, 6}, {0, 2, 7}, {1, 2, 8}, {1, 3, 5}, {1, 4, -4}, {2, 3, -3}, {2, 4, 9}, {3, 1, -2}, {4, 3, 7}, } V := 5 src := 0 // Bellman-Ford run here
The shortest path from 0 to 4 is 0 -> 1 -> 4 with total weight 6 + (-4) = 2, but better path is 0 -> 2 -> 3 -> 1 -> 4 with weight 7 + (-3) + (-2) + (-4) = -2.
package main import "fmt" func bellmanFord(edges [][]int, V, src int) (bool, []int) { dist := make([]int, V) for i := range dist { dist[i] = 1 << 30 } dist[src] = 0 for i := 0; i < V-1; i++ { for _, edge := range edges { u, v, w := edge[0], edge[1], edge[2] if dist[u] != 1<<30 && dist[u]+w < dist[v] { dist[v] = dist[u] + w } } } for _, edge := range edges { u, v, w := edge[0], edge[1], edge[2] if dist[u] != 1<<30 && dist[u]+w < dist[v] { return false, dist } } return true, dist } func main() { edges := [][]int{ {0, 1, 1}, {1, 2, -1}, {2, 3, -1}, {3, 1, -1}, } ok, dist := bellmanFord(edges, 4, 0) if !ok { fmt.Println("Negative cycle detected") } else { fmt.Println(dist) } }
The graph contains a negative cycle (1 -> 2 -> 3 -> 1). The algorithm detects it and returns false, so the program prints "Negative cycle detected".
