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

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

dijkstra.gno

// Package dijkstra finds the cheapest route from one node to every other node
// of a weighted directed graph, as a pure, reusable package.
//
// It is Dijkstra's algorithm with a binary min-heap keyed on node index, so a
// node is never queued twice and the queue never grows past the node count.
// Complexity is O((V+E) log V), and both V and E are capped (MaxNodes,
// MaxEdges) so a realm can reason about the gas before it calls.
//
// The result is *deterministic*. Two nodes sitting at the same distance settle
// in the order they were added to the graph, 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 shortest-path routine that broke
// ties by map iteration order would make a Render differ between validators,
// which is a consensus bug rather than a cosmetic one.
//
// Weights are non-negative by construction: AddEdge panics on a negative one.
// That is not a simplification, it is the precondition the algorithm needs. A
// settled node is never revisited, so one negative edge silently returns a
// wrong answer rather than an error.
//
// A live demo of this package is at
// [r/moul/x/daily/dijkstrademo](/r/moul/x/daily/dijkstrademo/v0).
package dijkstra

import (
	"errors"
	"strings"
)

const (
	// MaxNodes bounds the graph so a caller can size gas up front.
	MaxNodes = 512
	// MaxEdges bounds the arcs for the same reason. Both are deliberately
	// small: this is a package for a realm's routing table, not for a road
	// network.
	MaxEdges = 4000
	// Unreachable is the distance reported for a node no path reaches. It is
	// returned alongside ok=false, never on its own.
	Unreachable = -1
)

// ErrUnknownNode is returned by lookups naming a node the graph never saw.
var ErrUnknownNode = errors.New("dijkstra: unknown node")

type arc struct {
	to     int
	weight int
}

// Graph is a weighted directed graph over named nodes. The zero value is not
// usable, build one with New.
type Graph struct {
	names []string       // node index -> name, in insertion order
	index map[string]int // name -> node index. Looked up, never ranged over
	adj   [][]arc        // node index -> outgoing arcs, in insertion order
	edges int
}

// New returns an empty Graph.
func New() *Graph {
	return &Graph{index: map[string]int{}}
}

// 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 (g *Graph) AddNode(name string) int {
	if name == "" {
		panic("dijkstra: empty node name")
	}
	if i, ok := g.index[name]; ok {
		return i
	}
	if len(g.names) >= MaxNodes {
		panic("dijkstra: too many nodes")
	}
	i := len(g.names)
	g.names = append(g.names, name)
	g.index[name] = i
	g.adj = append(g.adj, nil)
	return i
}

// AddEdge records a one-way arc from -> to costing weight, registering either
// endpoint that is new. 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.
//
// It panics on a negative weight (the algorithm's precondition), on a
// self-loop (it can never shorten a path and is always a caller mistake), and
// past MaxEdges.
func (g *Graph) AddEdge(from, to string, weight int) {
	if weight < 0 {
		panic("dijkstra: negative weight")
	}
	if from == to {
		panic("dijkstra: self-loop")
	}
	if g.edges >= MaxEdges {
		panic("dijkstra: too many edges")
	}
	f := g.AddNode(from)
	t := g.AddNode(to)
	g.adj[f] = append(g.adj[f], arc{to: t, weight: weight})
	g.edges++
}

// AddUndirected records the same cost in both directions. It is two arcs and
// counts as two against MaxEdges, because that is what it is.
func (g *Graph) AddUndirected(a, b string, weight int) {
	g.AddEdge(a, b, weight)
	g.AddEdge(b, a, weight)
}

// Len returns the number of nodes.
func (g *Graph) Len() int { return len(g.names) }

// Edges returns the number of arcs. An AddUndirected call contributes two.
func (g *Graph) Edges() int { return g.edges }

// 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.
func (g *Graph) Names() []string {
	out := make([]string, len(g.names))
	copy(out, g.names)
	return out
}

// Has reports whether the graph knows a node by that name.
func (g *Graph) Has(name string) bool {
	_, ok := g.index[name]
	return ok
}

// Result holds one single-source run. It is a snapshot: mutating the graph
// afterwards does not update it.
type Result struct {
	g      *Graph
	src    int
	dist   []int
	prev   []int
	done   []bool
	order  []int
	relaxs int
}

// From runs the search outward from source and returns the distances to every
// node. It panics when source is not in the graph, because a typo'd source
// silently returning "nothing is reachable" is the failure mode this package
// exists to avoid.
func (g *Graph) From(source string) *Result {
	s, ok := g.index[source]
	if !ok {
		panic("dijkstra: unknown source: " + source)
	}

	n := len(g.names)
	r := &Result{g: g, src: s}
	r.dist = make([]int, n)
	r.prev = make([]int, n)
	r.done = make([]bool, n)
	for i := 0; i < n; i++ {
		r.dist[i] = Unreachable
		r.prev[i] = -1
	}

	q := newQueue(n, r.dist)
	r.dist[s] = 0
	q.push(s)

	for !q.empty() {
		u := q.pop()
		r.done[u] = true
		r.order = append(r.order, u)
		du := r.dist[u]

		for _, a := range g.adj[u] {
			v := a.to
			if r.done[v] {
				// Weights are non-negative, so a settled node can never be
				// improved. This is the line a negative edge would break.
				continue
			}
			cand := du + a.weight
			if r.dist[v] == Unreachable {
				r.dist[v] = cand
				r.prev[v] = u
				r.relaxs++
				q.push(v)
				continue
			}
			if cand < r.dist[v] {
				// Strictly cheaper, never merely equal: a tie leaves the
				// incumbent predecessor in place, which is what makes Path
				// reproducible rather than dependent on arc order.
				r.dist[v] = cand
				r.prev[v] = u
				r.relaxs++
				q.decreased(v)
			}
		}
	}
	return r
}

// Source returns the node the run started from.
func (r *Result) Source() string { return r.g.names[r.src] }

// Dist returns the total weight of the cheapest route to name. ok is false for
// a node no route reaches and for a name the graph does not know, which are
// different mistakes with the same remedy: check Has first if you need to tell
// them apart.
func (r *Result) Dist(name string) (dist int, ok bool) {
	i, known := r.g.index[name]
	if !known || r.dist[i] == Unreachable {
		return Unreachable, false
	}
	return r.dist[i], true
}

// Path returns the cheapest route to name, source first and name last. It
// returns nil when no route reaches name, and a one-element slice for the
// source itself.
func (r *Result) Path(name string) []string {
	i, known := r.g.index[name]
	if !known || r.dist[i] == Unreachable {
		return nil
	}
	var rev []int
	for at := i; at != -1; at = r.prev[at] {
		rev = append(rev, at)
	}
	out := make([]string, len(rev))
	for k, at := range rev {
		out[len(rev)-1-k] = r.g.names[at]
	}
	return out
}

// 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 (r *Result) PathString(name, sep string) string {
	p := r.Path(name)
	if p == nil {
		return ""
	}
	return strings.Join(p, sep)
}

// Via returns the node immediately before name on the cheapest route, and
// false for the source and for anything unreachable.
func (r *Result) Via(name string) (string, bool) {
	i, known := r.g.index[name]
	if !known || r.dist[i] == Unreachable || r.prev[i] == -1 {
		return "", false
	}
	return r.g.names[r.prev[i]], true
}

// Reachable returns how many nodes have a route, the source included.
func (r *Result) Reachable() int {
	return len(r.order)
}

// Order returns the nodes in the sequence the search settled them: the source
// first, then always the closest node still outstanding. That sequence is the
// algorithm, and a demo that shows it teaches more than one that prints only
// the answer.
func (r *Result) Order() []string {
	out := make([]string, len(r.order))
	for i, at := range r.order {
		out[i] = r.g.names[at]
	}
	return out
}

// Relaxations returns how many arcs the run actually improved a distance with.
// It is the honest cost figure: the arc count is what was looked at, this is
// what was paid for.
func (r *Result) Relaxations() int { return r.relaxs }

dijkstra_test.gno

package dijkstra

import (
	"strings"
	"testing"

	"gno.land/p/nt/uassert/v0"
)

// roads is the worked example used by most of the tests below, small enough to
// solve by hand. It is directed, and it is built so that the obvious answers
// are both wrong: the direct a -> c arc of 4 loses to a -> b -> c at 3, and c
// is the first node to offer a route to e (at 9) but d supplies a cheaper one
// (8) two steps later.
//
//	a -2-> b   a -4-> c   b -1-> c   b -3-> d   c -6-> e   d -3-> e
//
// f is an island: nothing reaches it, and it reaches nothing.
func roads() *Graph {
	g := New()
	g.AddEdge("a", "b", 2)
	g.AddEdge("a", "c", 4)
	g.AddEdge("b", "c", 1)
	g.AddEdge("b", "d", 3)
	g.AddEdge("c", "e", 6)
	g.AddEdge("d", "e", 3)
	g.AddNode("f")
	return g
}

func TestDistances(t *testing.T) {
	r := roads().From("a")

	tests := []struct {
		node string
		want int
		ok   bool
	}{
		{"a", 0, true},
		{"b", 2, true},
		{"c", 3, true}, // via b, not the direct arc of 4
		{"d", 5, true},
		{"e", 8, true}, // a,b,d,e at 8 beats a,b,c,e at 9
		{"f", Unreachable, false},
		{"nowhere", Unreachable, false},
	}
	for _, tt := range tests {
		got, ok := r.Dist(tt.node)
		uassert.Equal(t, tt.ok, ok, "ok for "+tt.node)
		uassert.Equal(t, tt.want, got, "dist for "+tt.node)
	}
}

func TestPaths(t *testing.T) {
	r := roads().From("a")

	tests := []struct {
		node string
		want string
	}{
		{"a", "a"},
		{"b", "a>b"},
		{"c", "a>b>c"},
		{"d", "a>b>d"},
		{"e", "a>b>d>e"},
		{"f", ""},
		{"nowhere", ""},
	}
	for _, tt := range tests {
		uassert.Equal(t, tt.want, r.PathString(tt.node, ">"), "path to "+tt.node)
	}

	uassert.Equal(t, 0, len(r.Path("f")), "unreachable path is nil")
	uassert.Equal(t, 1, len(r.Path("a")), "the source is a path of one")
}

// A node is settled in distance order, closest first, and that sequence is the
// algorithm. The island never settles at all.
func TestSettleOrder(t *testing.T) {
	r := roads().From("a")
	uassert.Equal(t, "a,b,c,d,e", strings.Join(r.Order(), ","))
	uassert.Equal(t, 5, r.Reachable())
	uassert.Equal(t, "a", r.Source())
}

// The tie-break is the property an on-chain Render depends on: two nodes at
// the same distance settle in the order they were added, never in map order,
// so the same graph gives the same answer on every validator.
func TestTiesSettleInInsertionOrder(t *testing.T) {
	g := New()
	for _, n := range []string{"hub", "west", "east", "north"} {
		g.AddNode(n)
	}
	g.AddEdge("hub", "west", 5)
	g.AddEdge("hub", "east", 5)
	g.AddEdge("hub", "north", 5)
	uassert.Equal(t, "hub,west,east,north", strings.Join(g.From("hub").Order(), ","))

	// Same graph, nodes declared in a different order: the settle order
	// follows the declaration, which is the whole claim.
	h := New()
	for _, n := range []string{"hub", "north", "east", "west"} {
		h.AddNode(n)
	}
	h.AddEdge("hub", "west", 5)
	h.AddEdge("hub", "east", 5)
	h.AddEdge("hub", "north", 5)
	uassert.Equal(t, "hub,north,east,west", strings.Join(h.From("hub").Order(), ","))
}

// An equal-cost route never displaces the incumbent, so the predecessor chain
// is the first one found rather than the last one tried.
func TestEqualCostKeepsTheFirstPredecessor(t *testing.T) {
	g := New()
	g.AddEdge("s", "left", 1)
	g.AddEdge("s", "right", 1)
	g.AddEdge("left", "t", 1)
	g.AddEdge("right", "t", 1)
	r := g.From("s")
	uassert.Equal(t, 2, mustDist(t, r, "t"))
	uassert.Equal(t, "s>left>t", r.PathString("t", ">"))

	via, ok := r.Via("t")
	uassert.True(t, ok)
	uassert.Equal(t, "left", via)

	_, ok = r.Via("s")
	uassert.False(t, ok, "the source has no predecessor")
}

// Parallel arcs are kept, and the search takes the cheapest of them.
func TestParallelArcsTakeTheCheapest(t *testing.T) {
	g := New()
	g.AddEdge("a", "b", 9)
	g.AddEdge("a", "b", 2)
	g.AddEdge("a", "b", 7)
	uassert.Equal(t, 3, g.Edges())
	uassert.Equal(t, 2, g.Len())
	uassert.Equal(t, 2, mustDist(t, g.From("a"), "b"))
}

func TestUndirectedGoesBothWays(t *testing.T) {
	g := New()
	g.AddUndirected("x", "y", 3)
	g.AddUndirected("y", "z", 4)
	uassert.Equal(t, 4, g.Edges(), "each undirected pair is two arcs")
	uassert.Equal(t, 7, mustDist(t, g.From("x"), "z"))
	uassert.Equal(t, 7, mustDist(t, g.From("z"), "x"))
}

// A zero-weight arc is legal and must not be mistaken for "no arc".
func TestZeroWeightArcs(t *testing.T) {
	g := New()
	g.AddEdge("a", "b", 0)
	g.AddEdge("b", "c", 0)
	r := g.From("a")
	uassert.Equal(t, 0, mustDist(t, r, "c"))
	uassert.Equal(t, "a>b>c", r.PathString("c", ">"))
}

// Relaxations counts improvements, not arcs looked at. On roads() the six
// arcs yield six improvements, but two of them are second thoughts: c drops
// from 4 to 3 once b settles, and e drops from 9 to 8 once d does.
func TestRelaxationsCountImprovements(t *testing.T) {
	uassert.Equal(t, 6, roads().From("a").Relaxations())
}

func TestGraphBookkeeping(t *testing.T) {
	g := roads()
	uassert.Equal(t, 6, g.Len())
	uassert.Equal(t, 6, g.Edges())
	uassert.Equal(t, "a,b,c,d,e,f", strings.Join(g.Names(), ","))
	uassert.True(t, g.Has("f"))
	uassert.False(t, g.Has("nowhere"))

	// AddNode is idempotent and returns the existing index.
	uassert.Equal(t, 0, g.AddNode("a"))
	uassert.Equal(t, 6, g.Len())

	// Names is a copy: reordering it must not reorder the graph.
	names := g.Names()
	names[0] = "mutated"
	uassert.Equal(t, "a", g.Names()[0])
}

// A search from an island reaches only itself, and that is not an error.
func TestSearchFromAnIsland(t *testing.T) {
	r := roads().From("f")
	uassert.Equal(t, 1, r.Reachable())
	uassert.Equal(t, "f", strings.Join(r.Order(), ","))
	uassert.Equal(t, 0, mustDist(t, r, "f"))
	_, ok := r.Dist("a")
	uassert.False(t, ok, "arcs are one-way, f reaches nothing")
}

// A Result is a snapshot. Adding arcs afterwards does not change what it says,
// which is what makes it safe to hold across a Render.
func TestResultIsASnapshot(t *testing.T) {
	g := New()
	g.AddEdge("a", "b", 10)
	r := g.From("a")
	g.AddEdge("a", "b", 1)
	uassert.Equal(t, 10, mustDist(t, r, "b"))
	uassert.Equal(t, 1, mustDist(t, g.From("a"), "b"))
}

// The preconditions are enforced at build time, where the caller can still do
// something about it, rather than silently returning a wrong shortest path.
func TestBuildPanics(cur realm, t *testing.T) {
	g := New()
	uassert.PanicsWithMessage(t, cur, "dijkstra: negative weight", func() { g.AddEdge("a", "b", -1) })
	uassert.PanicsWithMessage(t, cur, "dijkstra: self-loop", func() { g.AddEdge("a", "a", 1) })
	uassert.PanicsWithMessage(t, cur, "dijkstra: empty node name", func() { g.AddNode("") })
	uassert.PanicsWithMessage(t, cur, "dijkstra: unknown source: zz", func() { g.From("zz") })
	uassert.NotPanics(t, cur, func() { g.AddEdge("a", "b", 0) })
}

func TestCapacityPanics(cur realm, t *testing.T) {
	g := New()
	for i := 0; i < MaxNodes; i++ {
		g.AddNode(name(i))
	}
	uassert.Equal(t, MaxNodes, g.Len())
	uassert.PanicsWithMessage(t, cur, "dijkstra: too many nodes", func() { g.AddNode("one-too-many") })

	// Parallel arcs, so the edge cap is reached without tripping the node cap
	// first: MaxEdges is deliberately larger than MaxNodes.
	h := New()
	for i := 0; i < MaxEdges; i++ {
		h.AddEdge("hub", "spoke", 1)
	}
	uassert.Equal(t, MaxEdges, h.Edges())
	uassert.Equal(t, 2, h.Len())
	uassert.PanicsWithMessage(t, cur, "dijkstra: too many edges", func() { h.AddEdge("hub", "late", 1) })
}

// A long chain exercises the heap past the point where a linear scan would
// still look correct, and pins the cost at the same time.
func TestLongChain(t *testing.T) {
	g := New()
	for i := 0; i < 200; i++ {
		g.AddEdge(name(i), name(i+1), 2)
	}
	r := g.From(name(0))
	uassert.Equal(t, 400, mustDist(t, r, name(200)))
	uassert.Equal(t, 201, r.Reachable())
	uassert.Equal(t, 200, r.Relaxations(), "a chain improves each node exactly once")
	uassert.Equal(t, 201, len(r.Path(name(200))))
}

// mustDist fails the test rather than returning a zero that reads like a real
// distance.
func mustDist(t *testing.T, r *Result, node string) int {
	t.Helper()
	d, ok := r.Dist(node)
	if !ok {
		t.Fatalf("no route to %s", node)
	}
	return d
}

// name turns an index into a stable node name, so the generated graphs above
// do not depend on formatting helpers.
func name(i int) string {
	if i == 0 {
		return "n0"
	}
	var digits []byte
	for i > 0 {
		digits = append([]byte{byte('0' + i%10)}, digits...)
		i /= 10
	}
	return "n" + string(digits)
}

gnomod.toml

module = "gno.land/p/g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv/x/daily/dijkstra/v0"
gno = "0.9"

[addpkg]
  creator = "g1magld5ptgzaktqcexxq0pgq5lmdf0kz6re8hlv"
  height = 751591
  max_deposit = "10000000ugnot"

queue.gno

package dijkstra

// queue is the frontier: a binary min-heap of node indices ordered by their
// current distance, with a position table so a node already in the heap can be
// moved up when its distance improves.
//
// The alternative, pushing a second entry and discarding stale pops, is
// shorter and is what a generic priority queue forces on you. It also lets the
// heap grow to one entry per arc, which is the size this package refuses to
// let a caller guess at: here the heap holds at most one entry per node, so
// MaxNodes bounds the memory and MaxEdges bounds only the work.
//
// Ordering is total: distance first, then node index. Node indices are
// assigned in the order AddNode saw them, so an equal-distance tie resolves to
// the order the caller built the graph in, identically on every machine.
type queue struct {
	heap []int // heap positions -> node index
	pos  []int // node index -> heap position, -1 when not queued
	dist []int // the live distance table, read, never written
}

func newQueue(n int, dist []int) *queue {
	q := &queue{dist: dist, pos: make([]int, n)}
	for i := 0; i < n; i++ {
		q.pos[i] = -1
	}
	return q
}

func (q *queue) empty() bool { return len(q.heap) == 0 }

func (q *queue) less(a, b int) bool {
	if q.dist[a] != q.dist[b] {
		return q.dist[a] < q.dist[b]
	}
	return a < b
}

func (q *queue) swap(i, j int) {
	q.heap[i], q.heap[j] = q.heap[j], q.heap[i]
	q.pos[q.heap[i]] = i
	q.pos[q.heap[j]] = j
}

// push queues a node whose distance has just become finite.
func (q *queue) push(node int) {
	q.heap = append(q.heap, node)
	q.pos[node] = len(q.heap) - 1
	q.up(len(q.heap) - 1)
}

// decreased re-sifts a queued node after its distance dropped.
func (q *queue) decreased(node int) { q.up(q.pos[node]) }

// pop removes and returns the closest outstanding node.
func (q *queue) pop() int {
	top := q.heap[0]
	last := len(q.heap) - 1
	q.swap(0, last)
	q.heap = q.heap[:last]
	q.pos[top] = -1
	if last > 0 {
		q.down(0)
	}
	return top
}

func (q *queue) up(i int) {
	for i > 0 {
		parent := (i - 1) / 2
		if !q.less(q.heap[i], q.heap[parent]) {
			break
		}
		q.swap(i, parent)
		i = parent
	}
}

func (q *queue) down(i int) {
	n := len(q.heap)
	for {
		small := i
		if l := 2*i + 1; l < n && q.less(q.heap[l], q.heap[small]) {
			small = l
		}
		if r := 2*i + 2; r < n && q.less(q.heap[r], q.heap[small]) {
			small = r
		}
		if small == i {
			return
		}
		q.swap(i, small)
		i = small
	}
}