Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

v0 source pure

Package bellmanford finds the cheapest route from one node to every other node of a weighted directed graph whose arc...

Readme View source

gno.land/p/moul/x/daily/bellmanford/v0

Cheapest routes across a graph whose arcs may cost less than nothing: AddEdge, From, State, Dist, Path, Cycle.

 1import "gno.land/p/moul/x/daily/bellmanford/v0"
 2
 3g := bellmanford.New()
 4g.AddEdge("gate", "market", 4)
 5g.AddEdge("gate", "depot", 5)
 6g.AddEdge("depot", "market", -3)   // a rebate, which Dijkstra cannot take
 7
 8r := g.From("gate")
 9r.Dist("market")                   // → 2, true   (5-3 through depot, not the direct arc of 4)
10r.PathString("market", " -> ")     // → "gate -> depot -> market"
11r.State("market")                  // → Settled
12r.HasNegativeCycle()               // → false

A realm pricing a route across its own fee table has negative arcs the moment anything pays a rebate, a refund or a subsidy. dijkstra refuses them outright, which is the right call: it settles a node at its best known cost and never revisits it, so one negative arc would not raise an error later, it would return a confident wrong number. This is the search to use instead. It costs O(V*E) against O((V+E) log V), and the extra passes buy the only thing that matters here: the answer is right.

It also answers the question a single-pass search cannot even ask: whether a cheapest route exists. Go round a cycle whose arcs sum below zero and the total keeps falling, so there is no cheapest route to anything that cycle reaches, only cheaper ones. Those nodes report Unbounded rather than a number, Cycle hands back the ring itself, CycleWeight says what one turn of it is worth, and the nodes the cycle cannot reach keep their real distances. A fee table with one broken loop in it is still useful everywhere else, and failing the whole query would throw that away.

Four things to know before you use it:

  • Dist has no unreachable sentinel, and cannot have one. -1 is a legitimate distance here, so every value it could reserve is one a real route might have. With ok=false the int is 0 and means nothing at all. State is the call that tells you why: Unknown (never heard the name), Unreached (nothing gets there), Unbounded (too much gets there). They are three different mistakes and the remedies differ.
  • Rounds is the figure to watch, not the node count. The bound is V-1 passes over the arc list, and the real number is decided by the order the arcs were added in: the same 12-hop chain takes 2 passes declared front to back and 12 declared back to front. Declare arcs roughly along the direction traffic flows and most graphs settle in two.
  • Self-loops are legal, and AddUndirected deliberately does not exist. A negative self-loop is the smallest negative cycle there is, and refusing it would have hidden a case rather than simplified one. A negative arc recorded in both directions, on the other hand, is a negative cycle by construction, so the convenience method would be a trap with a friendly name.
  • A negative cycle elsewhere in the graph is not reported. Detection is relative to the source: if the source cannot reach the cycle, every distance this run gives is a real shortest path and HasNegativeCycle is false.

MaxNodes is 512, MaxEdges is 4000 and MaxWeight is 2^40. The first two bound the worst case at V*E relaxations, which is what lets a caller price the gas before it sends the transaction; the third keeps the largest total a path can carry well inside an int. Exceeding any of them panics at build time, where the caller can still do something about it.

The run is deterministic: arcs relax in the order they were added, every pass, and a relaxation that merely ties the incumbent never replaces it. A search that broke ties by map iteration order would make a Render differ between validators, which is a consensus bug rather than a cosmetic one.

A Result is a snapshot. Mutating the graph afterwards does not update it, which is what makes it safe to compute once and hold across a Render.

Live demo: r/moul/x/daily/bellmanforddemo.


Part of moul/gno-contracts — moul's versioned gno.land contracts. See the repository for the full catalog, build/test tooling, and usage.

🧪 Highly experimental — potentially vibe-coded. Not audited; may break, change, or be removed at any time. Do not use with anything of value. Full disclaimer: DISCLAIMER.

Overview

Package bellmanford finds the cheapest route from one node to every other node of a weighted directed graph whose arcs may cost LESS than nothing, as a pure, reusable package.

It is the Bellman-Ford algorithm: V-1 passes over the whole arc list, each pass relaxing every arc, stopping as soon as a pass changes nothing. That is O(V*E) against Dijkstra's O((V+E) log V), and the extra cost buys exactly one thing: a negative arc no longer produces a confidently wrong answer. A settle-and-never-revisit search reads a rebate, a refund or a subsidy as an ordinary cheap hop and misses that it reorders everything decided before it.

It also answers the question a shortest-path routine can only answer when it is allowed to look twice: whether a shortest path EXISTS. Go round a cycle whose arcs sum to less than zero and the total keeps falling, so there is no cheapest route to anything that cycle reaches, only cheaper ones. Such nodes report Unbounded rather than a number, the cycle itself is handed back by Result.Cycle, and nodes the cycle cannot reach keep their real distances. A realm pricing a route across its own fee table wants to be told that, loudly, rather than handed the distance after an arbitrary number of turns.

The run is deterministic. Arcs are relaxed in the order they were added, every pass, and a relaxation that merely ties the incumbent never replaces it, so the predecessor chain Path walks is the same on every node that runs the code. A search that broke ties by map iteration order would make a Render differ between validators, which is a consensus bug rather than a cosmetic one.

Where it differs from p/moul/x/daily/dijkstra(/p/moul/x/daily/dijkstra/v0), which is the right tool whenever every weight is non-negative:

  • Dist has no "unreachable" sentinel value. -1 is a legitimate distance here, so the int returned alongside ok=false carries no meaning at all.
  • Self-loops are allowed. A negative one is the smallest negative cycle there is, and refusing it would hide a case rather than simplify one.
  • There is no AddUndirected. A negative arc in both directions is a negative cycle by construction, so the convenience would be a trap.

A live demo of this package is at r/moul/x/daily/bellmanforddemo(/r/moul/x/daily/bellmanforddemo/v0).

Constants 2

const MaxNodes, MaxEdges, MaxWeight

 1const (
 2	// MaxNodes bounds the graph so a caller can size gas up front.
 3	MaxNodes = 512
 4	// MaxEdges bounds the arcs for the same reason. The work is V*E in the
 5	// worst case, so these two caps are what make that worst case a number
 6	// rather than a hope.
 7	MaxEdges = 4000
 8	// MaxWeight bounds a single arc's cost, in either direction. The bound on
 9	// a distance is not a path's length times this: while a negative cycle is
10	// still being relaxed, one pass can walk every one of MaxEdges arcs and the
11	// run makes up to MaxNodes passes, so a distance can drift as far as
12	// MaxNodes*MaxEdges*MaxWeight. driftBound below makes the compiler check
13	// that product fits.
14	MaxWeight = 1 << 40
15)
source

const Unknown, Unreached, Settled, Unbounded

 1const (
 2	// Unknown means the graph has never heard the name.
 3	Unknown State = iota
 4	// Unreached means no route leaves the source for it.
 5	Unreached
 6	// Settled means it has a finite cheapest route, which Dist returns.
 7	Settled
 8	// Unbounded means a negative cycle reaches it, so every route can be
 9	// beaten by going round once more and no cheapest route exists.
10	Unbounded
11)
source

Functions 1

func New

1func New() *Graph
source

New returns an empty Graph.

Types 3

type Graph

struct
1type Graph struct {
2	names []string       // node index -> name, in insertion order
3	index map[string]int // name -> node index. Looked up, never ranged over
4	arcs  []arc          // every arc, in insertion order: this is the relaxation order
5}
source

Graph is a weighted directed graph over named nodes. The zero value is not usable, build one with New.

Methods on Graph

func AddEdge

method on Graph
1func (g *Graph) AddEdge(from, to string, weight int)
source

AddEdge records a one-way arc from -> to costing weight, registering either endpoint that is new. The weight may be negative, which is the whole reason this package exists. Parallel arcs are kept rather than collapsed: the search takes the cheapest, and dropping the others would lose information a caller may want to render.

A self-loop is legal. A negative one is a one-arc negative cycle and is reported as such; a non-negative one can never improve a distance and is simply never relaxed.

It panics on a weight outside [-MaxWeight, MaxWeight], and past MaxEdges.

func AddNode

method on Graph
1func (g *Graph) AddNode(nm string) int
source

AddNode registers a node with no arcs and returns its index. Adding a node twice returns the existing index and changes nothing, which is how a caller declares an island that nothing reaches.

It panics on an empty name, and past MaxNodes.

func Edges

method on Graph
1func (g *Graph) Edges() int
source

Edges returns the number of arcs.

func From

method on Graph
1func (g *Graph) From(source string) *Result
source

From runs the search outward from source and returns what every node is worth. It panics when source is not in the graph, because a typo'd source silently reporting "nothing is reachable" is the failure mode this package exists to avoid.

It never panics on a negative cycle. A cycle is an answer, not an error, and the caller gets to decide what to do about it.

func Has

method on Graph
1func (g *Graph) Has(nm string) bool
source

Has reports whether the graph knows a node by that name.

func Len

method on Graph
1func (g *Graph) Len() int
source

Len returns the number of nodes.

func Names

method on Graph
1func (g *Graph) Names() []string
source

Names returns the node names in insertion order. The slice is a copy, so a caller cannot reorder the graph's own index by sorting it.

type Result

struct
 1type Result struct {
 2	names     []string       // the graph's names as of From, capped
 3	arcs      []arc          // the graph's arcs as of From, capped
 4	index     map[string]int // shared with the graph: always bounds-check against names
 5	src       int
 6	dist      []int
 7	prev      []int
 8	reached   []bool
 9	unbounded []bool
10	cycle     []int // a closed walk, first node repeated last. Empty when there is none
11	rounds    int
12	relaxs    int
13}
source

Result holds one single-source run. It is a snapshot: mutating the graph afterwards does not update it. It keeps its own views of the node names and the arc list, capped at their length when From ran, so a node or an arc added later is invisible to it rather than an index past its slices.

Methods on Result

func Cycle

method on Result
1func (r *Result) Cycle() []string
source

Cycle returns one negative cycle as a closed walk, first node repeated last, or nil when there is none. A graph may hold several; this is the one the first witness in arc order sits downstream of.

func CycleWeight

method on Result
1func (r *Result) CycleWeight() int
source

CycleWeight returns what one turn of the reported cycle costs, taking the cheapest arc for each hop, or 0 when there is no cycle. It is always negative when HasNegativeCycle is true, and that is worth asserting in a caller's test: it is the one number that proves the detection was real.

func Dist

method on Result
1func (r *Result) Dist(nm string) (int, bool)
source

Dist returns the total weight of the cheapest route to nm, and whether one exists at all.

The int returned with ok=false means NOTHING. There is no sentinel because there cannot be one: a negative total is a legitimate answer here, so any value this could return is also a value a real route could have. Call State when the reason matters.

func HasNegativeCycle

method on Result
1func (r *Result) HasNegativeCycle() bool
source

HasNegativeCycle reports whether a cycle whose arcs sum to less than zero is reachable from the source. A cycle elsewhere in the graph is not this run's problem and is not reported.

func Path

method on Result
1func (r *Result) Path(nm string) []string
source

Path returns the cheapest route to nm, source first and nm last. It returns nil whenever Dist would return ok=false, the unbounded case included: a route that can always be beaten is not a shortest path, and handing one back would be the lie this package is built to refuse.

func PathString

method on Result
1func (r *Result) PathString(nm, sep string) string
source

PathString renders Path joined with sep, or "" when there is no route. It exists so a Render does not have to carry its own join loop.

func Reachable

method on Result
1func (r *Result) Reachable() int
source

Reachable returns how many nodes a route leaves the source for, the source included and the unbounded ones counted: they are reached, they just have no cheapest route.

func Relaxations

method on Result
1func (r *Result) Relaxations() int
source

Relaxations returns how many arcs actually improved a distance. It is the honest cost figure: the arc count times the round count is what was looked at, this is what was paid for.

func Rounds

method on Result
1func (r *Result) Rounds() int
source

Rounds returns how many passes over the arc list the run made. The bound is V-1, and what decides the real figure is the order the arcs were added in, so this is the number to watch when gas matters.

A run that settles early makes one more pass to prove nothing moved, and that pass is counted here. A run that needs the full V-1 instead pays the separate detection pass, which is not.

func Source

method on Result
1func (r *Result) Source() string
source

Source returns the node the run started from.

func State

method on Result
1func (r *Result) State(nm string) State
source

State reports what the run can say about one node. It is the call to make before Dist whenever the difference between "nothing reaches it" and "a negative cycle reaches it" changes what the caller does.

func UnboundedNodes

method on Result
1func (r *Result) UnboundedNodes() []string
source

UnboundedNodes returns, in insertion order, every node a negative cycle reaches. It is empty when there is no cycle, and it is the blast radius: the nodes whose distance a less careful implementation would have reported.

func Via

method on Result
1func (r *Result) Via(nm string) (string, bool)
source

Via returns the node immediately before nm on the cheapest route, and false for the source and for anything without one.

type State

ident
1type State int
source

State is what a run can say about one node. It exists because "no distance" has two different causes here and they call for opposite reactions: nothing reaches the node, or too much does.

Methods on State

func String

method on State
1func (s State) String() string
source

String renders a State for a table or an error message.

Source Files 3