{"record":{"id":"16debc70a909f997","repo":"TheAlgorithms/Go","slug":"negative-weight-cycle-present","errorCode":null,"errorMessage":"negative weight cycle present","messagePattern":"negative weight cycle present","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"graph/bellmanford.go","lineNumber":45,"sourceCode":"\tfor n := 0; n < g.vertices; n++ {\n\n\t\t// Looping over all edges\n\t\tfor u, adjacents := range g.edges {\n\t\t\tfor v, weightUV := range adjacents {\n\n\t\t\t\t// If new shorter distance is found, update distance value (relaxation step)\n\t\t\t\tif newDistance := distances[u] + float64(weightUV); distances[v] > newDistance {\n\t\t\t\t\tdistances[v] = newDistance\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check for negative weight cycle\n\tfor u, adjacents := range g.edges {\n\t\tfor v, weightUV := range adjacents {\n\t\t\tif newDistance := distances[u] + float64(weightUV); distances[v] > newDistance {\n\t\t\t\treturn false, -1, errors.New(\"negative weight cycle present\")\n\t\t\t}\n\t\t}\n\t}\n\n\treturn distances[end] != INF, int(distances[end]), nil\n}\n","sourceCodeStart":27,"sourceCodeEnd":52,"githubUrl":"https://github.com/TheAlgorithms/Go/blob/5ba447ec5ff3d1213de65b92e726ee74c5d5cc19/graph/bellmanford.go#L27-L52","documentation":"After V iterations of Bellman-Ford relaxation, a further relaxation still shortens a distance, proving the graph contains a negative-weight cycle. BellmanFord returns (false, -1, err) because shortest paths are undefined in such a graph.","triggerScenarios":"Thrown at graph/bellmanford.go:45 when the library encounters an invalid state.","commonSituations":"See trigger scenarios.","solutions":["Remove or rewrite edges creating the negative cycle if the model allows","Detect and report the offending cycle (e.g. via Bellman-Ford predecessor tracking) before computing paths","Use an algorithm supporting negative cycles (e.g. cycle-cancellation for min-cost flow) if such graphs are legitimate input"],"exampleFix":null,"handlingStrategy":"fallback","validationCode":null,"typeGuard":null,"tryCatchPattern":null,"preventionTips":[],"tags":[],"backgroundTag":null,"analyzedSha":"5ba447ec5ff3d1213de65b92e726ee74c5d5cc19","analyzedAt":"2026-09-02T21:54:30.227Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-10T02:17:09.455Z"}