Skip to content

knotkit/graph

Provides breadth-first search, Dijkstra, topological order, and connected components over integer-vertex graphs, stored as adjacency lists, compressed sparse rows, or an adjacency matrix

import {
function compressedSparseRowGraph(options: GraphOptions): CompressedSparseRowGraph

An immutable graph stored as compressed sparse rows: one Int32Array of row offsets and one flat array of neighbor ids, plus a flat Float64Array of weights when the graph is weighted.

It is the layout for an edge set known up front: 4(n + 1) + 4m' bytes, plus 8m' when weighted, where m' is the stored arcs (2m undirected). Rows are contiguous, so a walk reads memory in order. A directed graph counts its in-degrees into one Int32Array on the first inDegree call, and builds its transposed rows only on the first forEachPredecessor call, keeping them and dropping the counts.

@param ― options - The vertex count, the two required flags, the multigraph flags, and the edges.

@throws ― {GraphInvalidInputError} With code INVALID_VERTEX_COUNT, INVALID_FLAG, INVALID_EDGE, INVALID_VERTEX, MISSING_WEIGHT, UNEXPECTED_WEIGHT, INVALID_WEIGHT, SELF_LOOP, or PARALLEL_EDGE when an option or an edge breaks the contract, or MAX_CAPACITY_EXCEEDED when storage cannot be allocated.

@example

const graph = compressedSparseRowGraph({
vertexCount: 4,
directed: true,
weighted: false,
edges: [[0, 1], [0, 2], [1, 3], [2, 3]],
})
graph.neighbors(0) // Int32Array [1, 2]

compressedSparseRowGraph
,
function topologicalOrder(adjacency: Adjacency): TopologicalOrderResult

Order the vertices so every edge points forward, or return one directed cycle that makes that impossible. O(n + m) on compressed-sparse-row and adjacency-list; it walks every row twice, so an adjacency-matrix costs O(n² / 32 + m) unweighted and O(n²) weighted.

Kahn's algorithm, starting from the vertices with no predecessor in ascending id and taking them first in, first out, so the order is the same on every layout. A cycle is an answer, not a failure: the result says which one it holds. A self-loop is a cycle of one vertex.

@throws ― {GraphInvalidInputError} With code DIRECTED_GRAPH_REQUIRED for an undirected graph, where every edge would be a cycle of two vertices; or, from a hand-written adjacency, INVALID_VERTEX or INVALID_WEIGHT for a neighbor or weight it reports, and INVALID_VERTEX_COUNT or INVALID_FLAG when it misstates its shape.

@example

const result = topologicalOrder(dependencies)
if (result.acyclic) build(result.order)
else report(result.cycle)

topologicalOrder
} from 'knotkit/graph'
// [course, prerequisite] pairs: each edge runs prerequisite -> course.
const
const prerequisites: readonly [readonly [1, 0], readonly [2, 0], readonly [3, 1], readonly [3, 2]]
prerequisites
= [
[1, 0],
[2, 0],
[3, 1],
[3, 2],
] as
type const = readonly [readonly [1, 0], readonly [2, 0], readonly [3, 1], readonly [3, 2]]
const
const
const courses: CompressedSparseRowGraph
courses
=
function compressedSparseRowGraph(options: GraphOptions): CompressedSparseRowGraph

An immutable graph stored as compressed sparse rows: one Int32Array of row offsets and one flat array of neighbor ids, plus a flat Float64Array of weights when the graph is weighted.

It is the layout for an edge set known up front: 4(n + 1) + 4m' bytes, plus 8m' when weighted, where m' is the stored arcs (2m undirected). Rows are contiguous, so a walk reads memory in order. A directed graph counts its in-degrees into one Int32Array on the first inDegree call, and builds its transposed rows only on the first forEachPredecessor call, keeping them and dropping the counts.

@param ― options - The vertex count, the two required flags, the multigraph flags, and the edges.

@throws ― {GraphInvalidInputError} With code INVALID_VERTEX_COUNT, INVALID_FLAG, INVALID_EDGE, INVALID_VERTEX, MISSING_WEIGHT, UNEXPECTED_WEIGHT, INVALID_WEIGHT, SELF_LOOP, or PARALLEL_EDGE when an option or an edge breaks the contract, or MAX_CAPACITY_EXCEEDED when storage cannot be allocated.

@example

const graph = compressedSparseRowGraph({
vertexCount: 4,
directed: true,
weighted: false,
edges: [[0, 1], [0, 2], [1, 3], [2, 3]],
})
graph.neighbors(0) // Int32Array [1, 2]

compressedSparseRowGraph
({
GraphOptions.vertexCount: number

Vertices are the integers 0 … vertexCount - 1. For 1-based input, pass n + 1 and leave vertex 0 isolated.

vertexCount
: 4,
GraphOptions.directed: boolean

Required: guessing it wrong changes every answer.

directed
: true,
GraphOptions.weighted: boolean

Required: a weighted graph needs a weight on every edge, and an unweighted graph rejects one.

weighted
: false,
GraphOptions.edges?: Iterable<GraphEdgeTuple> | GraphEdges | undefined

Edges to add, in order, as [from, to] or [from, to, weight] tuples or as the columns a graph's edges() returns. On an undirected graph [u, v] and [v, u] are the same edge.

edges
:
const prerequisites: readonly [readonly [1, 0], readonly [2, 0], readonly [3, 1], readonly [3, 2]]
prerequisites
.
ReadonlyArray<readonly [1, 0] | readonly [2, 0] | readonly [3, 1] | readonly [3, 2]>.map<readonly [0 | 1 | 2, 1 | 2 | 3]>(callbackfn: (value: readonly [1, 0] | readonly [2, 0] | readonly [3, 1] | readonly [3, 2], index: number, array: readonly (readonly [1, 0] | readonly [2, 0] | readonly [3, 1] | readonly [3, 2])[]) => readonly [0 | 1 | 2, 1 | 2 | 3], thisArg?: any): (readonly [0 | 1 | 2, 1 | 2 | 3])[]

Calls a defined callback function on each element of an array, and returns an array that contains the results.

@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

map
(([
course: 1 | 2 | 3
course
,
before: 0 | 1 | 2
before
]) => [
before: 0 | 1 | 2
before
,
course: 1 | 2 | 3
course
] as
type const = readonly [0 | 1 | 2, 1 | 2 | 3]
const
),
})
const
const result: TopologicalOrderResult
result
=
function topologicalOrder(adjacency: Adjacency): TopologicalOrderResult

Order the vertices so every edge points forward, or return one directed cycle that makes that impossible. O(n + m) on compressed-sparse-row and adjacency-list; it walks every row twice, so an adjacency-matrix costs O(n² / 32 + m) unweighted and O(n²) weighted.

Kahn's algorithm, starting from the vertices with no predecessor in ascending id and taking them first in, first out, so the order is the same on every layout. A cycle is an answer, not a failure: the result says which one it holds. A self-loop is a cycle of one vertex.

@throws ― {GraphInvalidInputError} With code DIRECTED_GRAPH_REQUIRED for an undirected graph, where every edge would be a cycle of two vertices; or, from a hand-written adjacency, INVALID_VERTEX or INVALID_WEIGHT for a neighbor or weight it reports, and INVALID_VERTEX_COUNT or INVALID_FLAG when it misstates its shape.

@example

const result = topologicalOrder(dependencies)
if (result.acyclic) build(result.order)
else report(result.cycle)

topologicalOrder
(
const courses: CompressedSparseRowGraph
courses
)
if (
const result: TopologicalOrderResult
result
.
acyclic: boolean
acyclic
)
const result: {
readonly acyclic: true;
readonly order: Int32Array;
}
result
.
order: Int32Array<ArrayBufferLike>

Every vertex, each after all of its predecessors.

order
// Int32Array [0, 1, 2, 3]
else
const result: {
readonly acyclic: false;
readonly cycle: Int32Array;
}
result
.
cycle: Int32Array<ArrayBufferLike>

The vertices of one directed cycle in walk order: each has an edge to the next, and the last to the first.

cycle
// the courses that wait on each other
graph.ts
import {
function compressedSparseRowGraph(options: GraphOptions): CompressedSparseRowGraph

An immutable graph stored as compressed sparse rows: one Int32Array of row offsets and one flat array of neighbor ids, plus a flat Float64Array of weights when the graph is weighted.

It is the layout for an edge set known up front: 4(n + 1) + 4m' bytes, plus 8m' when weighted, where m' is the stored arcs (2m undirected). Rows are contiguous, so a walk reads memory in order. A directed graph counts its in-degrees into one Int32Array on the first inDegree call, and builds its transposed rows only on the first forEachPredecessor call, keeping them and dropping the counts.

@param ― options - The vertex count, the two required flags, the multigraph flags, and the edges.

@throws ― {GraphInvalidInputError} With code INVALID_VERTEX_COUNT, INVALID_FLAG, INVALID_EDGE, INVALID_VERTEX, MISSING_WEIGHT, UNEXPECTED_WEIGHT, INVALID_WEIGHT, SELF_LOOP, or PARALLEL_EDGE when an option or an edge breaks the contract, or MAX_CAPACITY_EXCEEDED when storage cannot be allocated.

@example

const graph = compressedSparseRowGraph({
vertexCount: 4,
directed: true,
weighted: false,
edges: [[0, 1], [0, 2], [1, 3], [2, 3]],
})
graph.neighbors(0) // Int32Array [1, 2]

compressedSparseRowGraph
,
function dijkstra(adjacency: Adjacency, options: DijkstraOptions): DijkstraResult

Find the cheapest total cost from the nearest of sources to every vertex, with Dijkstra's algorithm over knotkit/heap's indexed priority queue. With target or a nonempty targets iterable, only settled vertices hold a distance and parent. An unreachable target leaves the search to exhaust the frontier. targets takes linear time to read and stores each distinct target once. The search uses O(n) extra memory and O((n + m) log n) time plus one row walk per expanded vertex, which is within that bound on compressed-sparse-row and adjacency-list and adds O(n² / 32) on an unweighted adjacency-matrix and O(n²) on a weighted one.

Named for the algorithm because it carries a precondition the caller must check: every cost is non-negative. Every edge out of an expanded vertex is priced and checked, including one into a vertex already settled, so a stored negative weight or a negative cost fails when the search first walks that edge rather than yielding a wrong distance.

Distances are float64 sums, subject to rounding. A sum that overflows to Infinity reads as unreached, as an explicitly infinite cost does.

@throws ― {GraphInvalidInputError} With code NEGATIVE_WEIGHT for a negative cost, INVALID_WEIGHT for a cost that is not a number or is NaN or a hand-written adjacency weight that is not a finite number, INVALID_VERTEX when a source, a target, or a reported neighbor is outside the graph, INVALID_VERTEX_COUNT or INVALID_FLAG when a hand-written adjacency misstates its shape, or MODIFIED_DURING_ITERATION when a cost callback changes the adjacency list being searched.

@example

const result = dijkstra(graph, { sources: [0], target: 4 })
result.distance[4] // cheapest cost from 0 to 4, or Infinity
path(result, 4) // Int32Array [0, …, 4]

dijkstra
,
function path(result: PathSource, target: number): Int32Array | undefined

The vertices of the path a search found from a source to target, source first, or undefined when the search never reached target. O(path length).

@throws ― {GraphInvalidInputError} With code INVALID_VERTEX when target is outside the result.

@example

path(breadthFirstSearch(graph, { sources: [0] }), 5) // Int32Array [0, 2, 5]

path
} from 'knotkit/graph'
const
const times: readonly [readonly [2, 1, 1], readonly [2, 3, 1], readonly [3, 4, 1]]
times
= [
[2, 1, 1],
[2, 3, 1],
[3, 4, 1],
] as
type const = readonly [readonly [2, 1, 1], readonly [2, 3, 1], readonly [3, 4, 1]]
const
const
const network: CompressedSparseRowGraph
network
=
function compressedSparseRowGraph(options: GraphOptions): CompressedSparseRowGraph

An immutable graph stored as compressed sparse rows: one Int32Array of row offsets and one flat array of neighbor ids, plus a flat Float64Array of weights when the graph is weighted.

It is the layout for an edge set known up front: 4(n + 1) + 4m' bytes, plus 8m' when weighted, where m' is the stored arcs (2m undirected). Rows are contiguous, so a walk reads memory in order. A directed graph counts its in-degrees into one Int32Array on the first inDegree call, and builds its transposed rows only on the first forEachPredecessor call, keeping them and dropping the counts.

@param ― options - The vertex count, the two required flags, the multigraph flags, and the edges.

@throws ― {GraphInvalidInputError} With code INVALID_VERTEX_COUNT, INVALID_FLAG, INVALID_EDGE, INVALID_VERTEX, MISSING_WEIGHT, UNEXPECTED_WEIGHT, INVALID_WEIGHT, SELF_LOOP, or PARALLEL_EDGE when an option or an edge breaks the contract, or MAX_CAPACITY_EXCEEDED when storage cannot be allocated.

@example

const graph = compressedSparseRowGraph({
vertexCount: 4,
directed: true,
weighted: false,
edges: [[0, 1], [0, 2], [1, 3], [2, 3]],
})
graph.neighbors(0) // Int32Array [1, 2]

compressedSparseRowGraph
({
GraphOptions.vertexCount: number

Vertices are the integers 0 … vertexCount - 1. For 1-based input, pass n + 1 and leave vertex 0 isolated.

vertexCount
: 5,
GraphOptions.directed: boolean

Required: guessing it wrong changes every answer.

directed
: true,
GraphOptions.weighted: boolean

Required: a weighted graph needs a weight on every edge, and an unweighted graph rejects one.

weighted
: true,
GraphOptions.edges?: Iterable<GraphEdgeTuple> | GraphEdges | undefined

Edges to add, in order, as [from, to] or [from, to, weight] tuples or as the columns a graph's edges() returns. On an undirected graph [u, v] and [v, u] are the same edge.

edges
:
const times: readonly [readonly [2, 1, 1], readonly [2, 3, 1], readonly [3, 4, 1]]
times
})
const
const delays: DijkstraResult
delays
=
function dijkstra(adjacency: Adjacency, options: DijkstraOptions): DijkstraResult

Find the cheapest total cost from the nearest of sources to every vertex, with Dijkstra's algorithm over knotkit/heap's indexed priority queue. With target or a nonempty targets iterable, only settled vertices hold a distance and parent. An unreachable target leaves the search to exhaust the frontier. targets takes linear time to read and stores each distinct target once. The search uses O(n) extra memory and O((n + m) log n) time plus one row walk per expanded vertex, which is within that bound on compressed-sparse-row and adjacency-list and adds O(n² / 32) on an unweighted adjacency-matrix and O(n²) on a weighted one.

Named for the algorithm because it carries a precondition the caller must check: every cost is non-negative. Every edge out of an expanded vertex is priced and checked, including one into a vertex already settled, so a stored negative weight or a negative cost fails when the search first walks that edge rather than yielding a wrong distance.

Distances are float64 sums, subject to rounding. A sum that overflows to Infinity reads as unreached, as an explicitly infinite cost does.

@throws ― {GraphInvalidInputError} With code NEGATIVE_WEIGHT for a negative cost, INVALID_WEIGHT for a cost that is not a number or is NaN or a hand-written adjacency weight that is not a finite number, INVALID_VERTEX when a source, a target, or a reported neighbor is outside the graph, INVALID_VERTEX_COUNT or INVALID_FLAG when a hand-written adjacency misstates its shape, or MODIFIED_DURING_ITERATION when a cost callback changes the adjacency list being searched.

@example

const result = dijkstra(graph, { sources: [0], target: 4 })
result.distance[4] // cheapest cost from 0 to 4, or Infinity
path(result, 4) // Int32Array [0, …, 4]

dijkstra
(
const network: CompressedSparseRowGraph
network
, {
DijkstraOptions.sources: Iterable<number>

Start vertices, all at distance 0.

sources
: [2] })
const delays: DijkstraResult
delays
.
DijkstraResult.distance: Float64Array<ArrayBufferLike>

The least total cost from the nearest source, or Infinity when unreached.

distance
// Float64Array [Infinity, 1, 0, 1, 2]
function path(result: PathSource, target: number): Int32Array | undefined

The vertices of the path a search found from a source to target, source first, or undefined when the search never reached target. O(path length).

@throws ― {GraphInvalidInputError} With code INVALID_VERTEX when target is outside the result.

@example

path(breadthFirstSearch(graph, { sources: [0] }), 5) // Int32Array [0, 2, 5]

path
(
const delays: DijkstraResult
delays
, 4) // Int32Array [2, 3, 4]
import {
function breadthFirstSearch(adjacency: Adjacency, options: BreadthFirstSearchOptions): BreadthFirstSearchResult

Find the fewest-hops distance from the nearest of sources to every vertex. O(n) extra memory, and O(n) time plus one row walk per reached vertex: O(n + m) on compressed-sparse-row and adjacency-list, but O(n² / 32 + m) on an unweighted adjacency-matrix and O(n²) on a weighted one, whose rows cost O(n / 32 + d) and O(n) whatever their degree.

Several sources make it a multi-source search, which is the "rotting oranges" and "walls and gates" shape. Neighbors are visited in ascending id, so the parents are the same on every layout.

@throws ― {GraphInvalidInputError} With code INVALID_VERTEX when a source, the target, or a reported neighbor is outside the graph; INVALID_WEIGHT when a hand-written adjacency reports a weight that is not a finite number; INVALID_VERTEX_COUNT or INVALID_FLAG when it misstates its shape; or MODIFIED_DURING_ITERATION when iterating sources changed the adjacency list being searched.

@example

const { distance } = breadthFirstSearch(graph, { sources: [0] })
distance[3] // hops from vertex 0 to vertex 3, or -1

breadthFirstSearch
,
function connectedComponents(adjacency: Adjacency): ConnectedComponentsResult

Label the connected components of an undirected graph. O(n + m) on compressed-sparse-row and adjacency-list; it walks every row once, so an adjacency-matrix costs O(n² / 32 + m) unweighted and O(n²) weighted.

Labels are assigned by breadth-first search from each unlabelled vertex in ascending id, so vertex 0 is always in component 0 and the labels are the same on every layout.

@throws ― {GraphInvalidInputError} With code UNDIRECTED_GRAPH_REQUIRED for a directed graph, whose weak and strong components are different questions; or, from a hand-written adjacency, INVALID_VERTEX or INVALID_WEIGHT for a neighbor or weight it reports, and INVALID_VERTEX_COUNT or INVALID_FLAG when it misstates its shape.

@example

const { count, component } = connectedComponents(graph)
component[3] === component[7] // whether 3 and 7 are connected

connectedComponents
,
function gridAdjacency(options: GridAdjacencyOptions): GridAdjacency

Treat a board of cells as a graph without storing it: each cell is a vertex, and each move to a neighboring cell is an edge of weight 1.

Every algorithm that takes an Adjacency accepts the result, which is all but floydWarshall: the fewest moves through a maze is one breadthFirstSearch, and the islands are connectedComponents. A closed cell is still a vertex, an isolated one with a component of its own, so count islands as the distinct labels of the open cells, as in the example. Moves are visited in ascending cell order. Memory is O(1); a walk over one cell is O(1) plus the callbacks.

@throws ― {GraphInvalidInputError} With code INVALID_GRID when rows or columns is not a positive integer, when the board would hold more than GRAPH_MAX_VERTEX_COUNT cells, or when connectivity is not 4 or 8.

@example

const grid = [[1, 1, 0], [0, 1, 0], [1, 0, 1]]
const open = (cell: number) => grid[Math.floor(cell / 3)][cell % 3] === 1
const board = gridAdjacency({ rows: 3, columns: 3, open })
board.cell(1, 1) // 4
const { component } = connectedComponents(board)
const islands = new Set<number>()
for (let cell = 0; cell < board.vertexCount; cell += 1) if (open(cell)) islands.add(component[cell])
islands.size // 3; connectedComponents(board).count is 7, one per water cell as well

gridAdjacency
} from 'knotkit/graph'
const
const grid: number[][]
grid
= [
[2, 1, 1],
[1, 1, 0],
[0, 1, 1],
]
const
const board: GridAdjacency
board
=
function gridAdjacency(options: GridAdjacencyOptions): GridAdjacency

Treat a board of cells as a graph without storing it: each cell is a vertex, and each move to a neighboring cell is an edge of weight 1.

Every algorithm that takes an Adjacency accepts the result, which is all but floydWarshall: the fewest moves through a maze is one breadthFirstSearch, and the islands are connectedComponents. A closed cell is still a vertex, an isolated one with a component of its own, so count islands as the distinct labels of the open cells, as in the example. Moves are visited in ascending cell order. Memory is O(1); a walk over one cell is O(1) plus the callbacks.

@throws ― {GraphInvalidInputError} With code INVALID_GRID when rows or columns is not a positive integer, when the board would hold more than GRAPH_MAX_VERTEX_COUNT cells, or when connectivity is not 4 or 8.

@example

const grid = [[1, 1, 0], [0, 1, 0], [1, 0, 1]]
const open = (cell: number) => grid[Math.floor(cell / 3)][cell % 3] === 1
const board = gridAdjacency({ rows: 3, columns: 3, open })
board.cell(1, 1) // 4
const { component } = connectedComponents(board)
const islands = new Set<number>()
for (let cell = 0; cell < board.vertexCount; cell += 1) if (open(cell)) islands.add(component[cell])
islands.size // 3; connectedComponents(board).count is 7, one per water cell as well

gridAdjacency
({
GridAdjacencyOptions.rows: number

Number of rows, a positive integer.

rows
: 3,
GridAdjacencyOptions.columns: number

Number of columns, a positive integer.

columns
: 3,
GridAdjacencyOptions.open?: ((cell: number) => boolean) | undefined

Whether a cell can be entered or left at all. A closed cell has no edges, and the grid stays undirected.

open
: (
cell: number
cell
) =>
const grid: number[][]
grid
[
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.floor(x: number): number

Returns the greatest integer less than or equal to its numeric argument.

@param ― x A numeric expression.

floor
(
cell: number
cell
/ 3)][
cell: number
cell
% 3] !== 0 })
const {
const distance: Int32Array<ArrayBufferLike>

Hops from the nearest source, or -1 when unreached.

distance
} =
function breadthFirstSearch(adjacency: Adjacency, options: BreadthFirstSearchOptions): BreadthFirstSearchResult

Find the fewest-hops distance from the nearest of sources to every vertex. O(n) extra memory, and O(n) time plus one row walk per reached vertex: O(n + m) on compressed-sparse-row and adjacency-list, but O(n² / 32 + m) on an unweighted adjacency-matrix and O(n²) on a weighted one, whose rows cost O(n / 32 + d) and O(n) whatever their degree.

Several sources make it a multi-source search, which is the "rotting oranges" and "walls and gates" shape. Neighbors are visited in ascending id, so the parents are the same on every layout.

@throws ― {GraphInvalidInputError} With code INVALID_VERTEX when a source, the target, or a reported neighbor is outside the graph; INVALID_WEIGHT when a hand-written adjacency reports a weight that is not a finite number; INVALID_VERTEX_COUNT or INVALID_FLAG when it misstates its shape; or MODIFIED_DURING_ITERATION when iterating sources changed the adjacency list being searched.

@example

const { distance } = breadthFirstSearch(graph, { sources: [0] })
distance[3] // hops from vertex 0 to vertex 3, or -1

breadthFirstSearch
(
const board: GridAdjacency
board
, {
BreadthFirstSearchOptions.sources: Iterable<number>

Start vertices, all at distance 0. A repeated source is ignored after its first appearance.

sources
: [
const board: GridAdjacency
board
.
GridAdjacency.cell: (row: number, column: number) => number

The vertex of the cell at (row, column).

@throws ― {GraphInvalidInputError} With code INVALID_VERTEX when the position is off the board.

cell
(0, 0)] })
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.max(...values: number[]): number

Returns the larger of a set of supplied numeric expressions.

@param ― values Numeric expressions to be evaluated.

max
(...
const distance: Int32Array<ArrayBufferLike>

Hops from the nearest source, or -1 when unreached.

distance
) // 4 minutes until the last orange rots
// A closed cell is still a vertex, alone in its own component, so count patches among the open cells.
const {
const component: Int32Array<ArrayBufferLike>

The component label of each vertex, in 0 … count - 1, numbered in order of each component's smallest vertex.

component
} =
function connectedComponents(adjacency: Adjacency): ConnectedComponentsResult

Label the connected components of an undirected graph. O(n + m) on compressed-sparse-row and adjacency-list; it walks every row once, so an adjacency-matrix costs O(n² / 32 + m) unweighted and O(n²) weighted.

Labels are assigned by breadth-first search from each unlabelled vertex in ascending id, so vertex 0 is always in component 0 and the labels are the same on every layout.

@throws ― {GraphInvalidInputError} With code UNDIRECTED_GRAPH_REQUIRED for a directed graph, whose weak and strong components are different questions; or, from a hand-written adjacency, INVALID_VERTEX or INVALID_WEIGHT for a neighbor or weight it reports, and INVALID_VERTEX_COUNT or INVALID_FLAG when it misstates its shape.

@example

const { count, component } = connectedComponents(graph)
component[3] === component[7] // whether 3 and 7 are connected

connectedComponents
(
const board: GridAdjacency
board
)
const
const patches: Set<number>
patches
= new
var Set: SetConstructor
new <number>(iterable?: Iterable<number> | null | undefined) => Set<number> (+1 overload)
Set
<number>()
for (let
let cell: number
cell
= 0;
let cell: number
cell
<
const board: GridAdjacency
board
.
Adjacency.vertexCount: number

Vertices are the integers 0 … vertexCount - 1.

vertexCount
;
let cell: number
cell
+= 1)
if (
const grid: number[][]
grid
[
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.floor(x: number): number

Returns the greatest integer less than or equal to its numeric argument.

@param ― x A numeric expression.

floor
(
let cell: number
cell
/ 3)][
let cell: number
cell
% 3] !== 0)
const patches: Set<number>
patches
.
Set<number>.add(value: number): Set<number>

Appends a new element with a specified value to the end of the Set.

add
(
const component: Int32Array<ArrayBufferLike>

The component label of each vertex, in 0 … count - 1, numbered in order of each component's smallest vertex.

component
[
let cell: number
cell
])
const patches: Set<number>
patches
.
Set<number>.size: number

@returns ― the number of (unique) elements in Set.

size
// 1 patch of oranges; connectedComponents(board).count is 3, counting each empty cell
import {
function adjacencyListGraph(options: GraphOptions): MutableGraph

A mutable graph stored as one sorted row per vertex, each row a slot with spare capacity in one shared Int32Array of neighbor ids, plus a parallel Float64Array of weights when the graph is weighted.

It is the one layout that grows after construction, through addVertex, addEdge, and deleteEdge. A row that outgrows its slot moves to the end of the shared array with doubled capacity, and the array is compacted once dead slots and spare capacity outweigh the stored arcs, so a graph that shrinks gives its memory back. An isolated vertex costs 12 bytes. A directed graph also keeps a reverse row per vertex for predecessor queries, which doubles its memory.

addEdge keeps the row sorted, which costs O(log d + d) for a vertex of degree d. Building from options.edges is O(n + m), so a large edge set known up front belongs in options.edges rather than in a loop of addEdge calls.

@param ― options - The vertex count, the two required flags, the multigraph flags, and the edges.

@throws ― {GraphInvalidInputError} With code INVALID_VERTEX_COUNT, INVALID_FLAG, INVALID_EDGE, INVALID_VERTEX, MISSING_WEIGHT, UNEXPECTED_WEIGHT, INVALID_WEIGHT, SELF_LOOP, or PARALLEL_EDGE when an option or an edge breaks the contract, or MAX_CAPACITY_EXCEEDED when storage cannot be allocated.

@example

const graph = adjacencyListGraph({ vertexCount: 2, directed: false, weighted: true })
const city = graph.addVertex() // 2
graph.addEdge(0, city, 7)
graph.hasEdge(city, 0) // true

adjacencyListGraph
} from 'knotkit/graph'
const
const roads: MutableGraph
roads
=
function adjacencyListGraph(options: GraphOptions): MutableGraph

A mutable graph stored as one sorted row per vertex, each row a slot with spare capacity in one shared Int32Array of neighbor ids, plus a parallel Float64Array of weights when the graph is weighted.

It is the one layout that grows after construction, through addVertex, addEdge, and deleteEdge. A row that outgrows its slot moves to the end of the shared array with doubled capacity, and the array is compacted once dead slots and spare capacity outweigh the stored arcs, so a graph that shrinks gives its memory back. An isolated vertex costs 12 bytes. A directed graph also keeps a reverse row per vertex for predecessor queries, which doubles its memory.

addEdge keeps the row sorted, which costs O(log d + d) for a vertex of degree d. Building from options.edges is O(n + m), so a large edge set known up front belongs in options.edges rather than in a loop of addEdge calls.

@param ― options - The vertex count, the two required flags, the multigraph flags, and the edges.

@throws ― {GraphInvalidInputError} With code INVALID_VERTEX_COUNT, INVALID_FLAG, INVALID_EDGE, INVALID_VERTEX, MISSING_WEIGHT, UNEXPECTED_WEIGHT, INVALID_WEIGHT, SELF_LOOP, or PARALLEL_EDGE when an option or an edge breaks the contract, or MAX_CAPACITY_EXCEEDED when storage cannot be allocated.

@example

const graph = adjacencyListGraph({ vertexCount: 2, directed: false, weighted: true })
const city = graph.addVertex() // 2
graph.addEdge(0, city, 7)
graph.hasEdge(city, 0) // true

adjacencyListGraph
({
GraphOptions.vertexCount: number

Vertices are the integers 0 … vertexCount - 1. For 1-based input, pass n + 1 and leave vertex 0 isolated.

vertexCount
: 2,
GraphOptions.directed: boolean

Required: guessing it wrong changes every answer.

directed
: false,
GraphOptions.weighted: boolean

Required: a weighted graph needs a weight on every edge, and an unweighted graph rejects one.

weighted
: true })
const
const town: number
town
=
const roads: MutableGraph
roads
.
MutableGraph.addVertex: () => number

Add an isolated vertex. O(1) amortized.

@returns ― The new vertex, which is the old vertexCount.

@throws ― {GraphInvalidInputError} With code MAX_CAPACITY_EXCEEDED past GRAPH_MAX_VERTEX_COUNT.

addVertex
() // 2
const roads: MutableGraph
roads
.
MutableGraph.addEdge: (from: number, to: number, weight?: number) => boolean

Add an edge. O(log d + d), where d is the endpoint's degree, because the row stays sorted.

@returns ― true when an edge was added; false when the graph is simple and already holds the same edge with the same weight.

@throws ― {GraphInvalidInputError} With code INVALID_VERTEX, MISSING_WEIGHT, UNEXPECTED_WEIGHT, INVALID_WEIGHT, SELF_LOOP, or PARALLEL_EDGE.

addEdge
(0,
const town: number
town
, 7) // true
const roads: MutableGraph
roads
.
MutableGraph.addEdge: (from: number, to: number, weight?: number) => boolean

Add an edge. O(log d + d), where d is the endpoint's degree, because the row stays sorted.

@returns ― true when an edge was added; false when the graph is simple and already holds the same edge with the same weight.

@throws ― {GraphInvalidInputError} With code INVALID_VERTEX, MISSING_WEIGHT, UNEXPECTED_WEIGHT, INVALID_WEIGHT, SELF_LOOP, or PARALLEL_EDGE.

addEdge
(
const town: number
town
, 0, 7) // false: the same road, already stored
const roads: MutableGraph
roads
.
MutableGraph.deleteEdge: (from: number, to: number) => boolean

Delete every copy of the edge from from to to.

@returns ― Whether any copy existed.

@throws ― {GraphInvalidInputError} With code INVALID_VERTEX when an endpoint is outside the graph.

deleteEdge
(0,
const town: number
town
) // true
import {
function breadthFirstSearch(adjacency: Adjacency, options: BreadthFirstSearchOptions): BreadthFirstSearchResult

Find the fewest-hops distance from the nearest of sources to every vertex. O(n) extra memory, and O(n) time plus one row walk per reached vertex: O(n + m) on compressed-sparse-row and adjacency-list, but O(n² / 32 + m) on an unweighted adjacency-matrix and O(n²) on a weighted one, whose rows cost O(n / 32 + d) and O(n) whatever their degree.

Several sources make it a multi-source search, which is the "rotting oranges" and "walls and gates" shape. Neighbors are visited in ascending id, so the parents are the same on every layout.

@throws ― {GraphInvalidInputError} With code INVALID_VERTEX when a source, the target, or a reported neighbor is outside the graph; INVALID_WEIGHT when a hand-written adjacency reports a weight that is not a finite number; INVALID_VERTEX_COUNT or INVALID_FLAG when it misstates its shape; or MODIFIED_DURING_ITERATION when iterating sources changed the adjacency list being searched.

@example

const { distance } = breadthFirstSearch(graph, { sources: [0] })
distance[3] // hops from vertex 0 to vertex 3, or -1

breadthFirstSearch
, type
(alias) interface Adjacency
import Adjacency

The smallest record every algorithm reads: how many vertices there are, whether edges have a direction, and a walk over one vertex's neighbors.

Every

Graph

is one, gridAdjacency returns one, and a caller can write one by hand for a graph it never stores, such as the words one letter apart from a given word.

Adjacency
} from 'knotkit/graph'
const
const words: string[]
words
= ['hot', 'dot', 'dog', 'cog', 'lot', 'log']
const
const oneLetterApart: (a: string, b: string) => boolean
oneLetterApart
= (
a: string
a
: string,
b: string
b
: string) => [...
a: string
a
].
Array<string>.filter(predicate: (value: string, index: number, array: string[]) => unknown, thisArg?: any): string[] (+1 overload)

Returns the elements of an array that meet the condition specified in a callback function.

@param ― predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.

@param ― thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.

filter
((
letter: string
letter
,
index: number
index
) =>
letter: string
letter
!==
b: string
b
[
index: number
index
]).
Array<string>.length: number

Gets or sets the length of the array. This is a number one higher than the highest index in the array.

length
=== 1
const
const ladder: Adjacency
ladder
:
(alias) interface Adjacency
import Adjacency

The smallest record every algorithm reads: how many vertices there are, whether edges have a direction, and a walk over one vertex's neighbors.

Every

Graph

is one, gridAdjacency returns one, and a caller can write one by hand for a graph it never stores, such as the words one letter apart from a given word.

Adjacency
= {
Adjacency.vertexCount: number

Vertices are the integers 0 … vertexCount - 1.

vertexCount
:
const words: string[]
words
.
Array<string>.length: number

Gets or sets the length of the array. This is a number one higher than the highest index in the array.

length
,
Adjacency.directed: boolean

Whether an edge from u to v leaves v without a way back to u.

directed
: false,
Adjacency.forEachNeighbor: (vertex: number, visit: (neighbor: number, weight: number) => void) => void

Call visit(neighbor, weight) once per stored edge out of vertex, in ascending neighbor id, with parallel copies in insertion order. An unweighted edge reports weight 1. A hand-written adjacency reports a finite number: an algorithm reading it throws INVALID_VERTEX for a neighbor outside the graph and INVALID_WEIGHT for any other weight.

@throws ― {GraphInvalidInputError} With code INVALID_VERTEX when vertex is not in 0 … vertexCount - 1.

forEachNeighbor
: (
word: number
word
,
visit: (neighbor: number, weight: number) => void
visit
) => {
for (let
let other: number
other
= 0;
let other: number
other
<
const words: string[]
words
.
Array<string>.length: number

Gets or sets the length of the array. This is a number one higher than the highest index in the array.

length
;
let other: number
other
+= 1) if (
const oneLetterApart: (a: string, b: string) => boolean
oneLetterApart
(
const words: string[]
words
[
word: number
word
],
const words: string[]
words
[
let other: number
other
]))
visit: (neighbor: number, weight: number) => void
visit
(
let other: number
other
, 1)
},
}
function breadthFirstSearch(adjacency: Adjacency, options: BreadthFirstSearchOptions): BreadthFirstSearchResult

Find the fewest-hops distance from the nearest of sources to every vertex. O(n) extra memory, and O(n) time plus one row walk per reached vertex: O(n + m) on compressed-sparse-row and adjacency-list, but O(n² / 32 + m) on an unweighted adjacency-matrix and O(n²) on a weighted one, whose rows cost O(n / 32 + d) and O(n) whatever their degree.

Several sources make it a multi-source search, which is the "rotting oranges" and "walls and gates" shape. Neighbors are visited in ascending id, so the parents are the same on every layout.

@throws ― {GraphInvalidInputError} With code INVALID_VERTEX when a source, the target, or a reported neighbor is outside the graph; INVALID_WEIGHT when a hand-written adjacency reports a weight that is not a finite number; INVALID_VERTEX_COUNT or INVALID_FLAG when it misstates its shape; or MODIFIED_DURING_ITERATION when iterating sources changed the adjacency list being searched.

@example

const { distance } = breadthFirstSearch(graph, { sources: [0] })
distance[3] // hops from vertex 0 to vertex 3, or -1

breadthFirstSearch
(
const ladder: Adjacency
ladder
, {
BreadthFirstSearchOptions.sources: Iterable<number>

Start vertices, all at distance 0. A repeated source is ignored after its first appearance.

sources
: [0] }).
BreadthFirstSearchResult.distance: Int32Array<ArrayBufferLike>

Hops from the nearest source, or -1 when unreached.

distance
[3] // 3 steps from "hot" to "cog"
import { __GRAPH_LAYOUTS } from 'knotkit/graph'
const { directed, weighted, parallelEdges, selfLoops } = mutable
const frozen = __GRAPH_LAYOUTS['compressed-sparse-row']({
vertexCount: mutable.vertexCount,
directed,
weighted,
parallelEdges,
selfLoops,
edges: mutable.edges(),
})
const
const ids: Map<string, number>
ids
= new
var Map: MapConstructor
new <string, number>(iterable?: Iterable<readonly [string, number]> | null | undefined) => Map<string, number> (+3 overloads)
Map
<string, number>()
const
const id: (key: string) => number
id
= (
key: string
key
: string) =>
const ids: Map<string, number>
ids
.
Map<string, number>.get(key: string): number | undefined

Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map.

@returns ― Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned.

get
(
key: string
key
) ?? (
const ids: Map<string, number>
ids
.
Map<string, number>.set(key: string, value: number): Map<string, number>

Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated.

set
(
key: string
key
,
const ids: Map<string, number>
ids
.
Map<string, number>.size: number

@returns ― the number of elements in the Map.

size
),
const ids: Map<string, number>
ids
.
Map<string, number>.size: number

@returns ― the number of elements in the Map.

size
- 1)
  • find the fewest-hops route between two points or the cheapest routes to selected destinations, all reachable points, or between every pair on a small graph
  • order tasks, builds, or courses so every dependency comes first, or find the cycle that makes that impossible
  • count the islands or connected pieces of a map, a grid, or a network, and say which piece each item is in
  • decide whether one item can reach another, and list the steps of the path between them
  • ask who depends on an item and what it depends on, with in-degree and out-degree
  • store a graph from an edge list as compact typed arrays, and persist it as bytes
FactoryChoose whenCost
compressedSparseRowGraph
kind compressed-sparse-row
the edge set is known when you build the graph, whatever its density4(n + 1) + 4m' bytes, plus 8m' weighted, where m' is the stored arcs (about 2m undirected), plus 4n bytes once inDegree is asked on a directed graph; breadth-first search measured within 1.2 times of a hand-written CSR loop over the same rows at 100,000 vertices of degree 10
adjacencyListGraph
kind adjacency-list
edges or vertices arrive after the graph is built12n + 4m' bytes built from edges, plus 8m' weighted, doubled for reverse rows when directed, and up to about twice that after edits until a compaction; 4.6 bytes per stored arc undirected and 5.2 directed at degree 10, against 4.2 and 4.4 for compressed-sparse-row; addEdge is O(log d + d) amortized, and breadth-first search measured within 1.3 times of compressed-sparse-row, and within 1.11 times from degree 10 up
adjacencyMatrixGraph
kind adjacency-matrix
no vertex pair repeats an edge, at least 5% of vertex pairs are edges, you probe hasEdge, and n² / 8 bytes (8n² weighted) fit in 256 MiBn² / 8 bytes unweighted and 8n² weighted whatever the edge count; hasEdge measured 2.8 to 3.2 times faster than the other layouts at 25% density, and searches 4 to 11 times slower because every walk scans the absent pairs

Performance and benchmarks for this module

{"v":1,"box":[73.1806,94.1597,717.7333,437.3555],"x":{"s":"log","lim":[0.77916457966,328.557029776],"inv":false,"g":0,"t":"Mean out-degree (arcs per vertex); density is degree / 2,048","tk":[[1,"1"],[4,"4"],[16,"16"],[29,"29"],[63,"63"],[256,"256"]],"b":10},"y":{"s":"log","lim":[12.4632779334,5321.24757663],"inv":false,"g":0,"tk":[[16,"16"],[64,"64"],[512,"512"],[4096,"4,096"]],"b":10},"ti":"At 2,048 vertices the bit matrix beats packed rows above 63 arcs per vertex","a":[{"k":"line","c":"#fffff8","s":"x","d":[1,64,2,80,4,112,8,176,16,304,32,560,64,1072,128,2096,256,4144],"p":[99.79,344.65,173.71,332,247.62,312.94,321.54,287.33,395.46,256.36,469.37,221.74,543.29,184.95,617.21,146.95,691.12,108.33]},{"k":"line","c":"#c4501b","s":"x","d":[1,64,2,80,4,112,8,176,16,304,32,560,64,1072,128,2096,256,4144],"p":[99.79,344.65,173.71,332,247.62,312.94,321.54,287.33,395.46,256.36,469.37,221.74,543.29,184.95,617.21,146.95,691.12,108.33]},{"k":"line","c":"#fffff8","s":"x","d":[1,16.00390625,2,24.00390625,4,40.00390625,8,72.00390625,16,136.00390625,32,264.00390625,64,520.00390625,128,1032.00390625,256,2056.00390625],"p":[99.79,423.19,173.71,400.22,247.62,371.27,321.54,337.97,395.46,301.93,469.37,264.35,543.29,225.94,617.21,187.1,691.12,148.04]},{"k":"line","c":"#1d5fa6","s":"x","d":[1,16.00390625,2,24.00390625,4,40.00390625,8,72.00390625,16,136.00390625,32,264.00390625,64,520.00390625,128,1032.00390625,256,2056.00390625],"p":[99.79,423.19,173.71,400.22,247.62,371.27,321.54,337.97,395.46,301.93,469.37,264.35,543.29,225.94,617.21,187.1,691.12,148.04]},{"k":"line","c":"#fffff8","s":"x","d":[1,512,2,512,4,512,8,512,16,512,32,512,64,512,128,512,256,512],"p":[99.79,226.82,173.71,226.82,247.62,226.82,321.54,226.82,395.46,226.82,469.37,226.82,543.29,226.82,617.21,226.82,691.12,226.82]},{"k":"line","c":"#5b6b7c","s":"x","d":[1,512,2,512,4,512,8,512,16,512,32,512,64,512,128,512,256,512],"p":[99.79,226.82,173.71,226.82,247.62,226.82,321.54,226.82,395.46,226.82,469.37,226.82,543.29,226.82,617.21,226.82,691.12,226.82]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"line","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"line","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#c4501b"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#5b6b7c"}],"lg":[]} 1 4 16 29 63 256 Mean out-degree (arcs per vertex); density is degree / 2,048 16 64 512 4,096 list ties at 1.4% rows tie at 3.1% Modeled buffer size (KiB) Adjacency list (both directions) Compressed sparse rows Adjacency matrix At 2,048 vertices the bit matrix beats packed rows above 63 arcs per vertex
{"v":1,"box":[73.1806,122.3921,269.7333,437.3555],"x":{"s":"log","lim":[0.77916457966,328.557029776],"inv":false,"g":0,"t":"Mean out-degree (arcs per vertex); density is degree / 2,048","tk":[[1,"1"],[4,"4"],[16,"16"],[29,"29"],[63,"63"],[256,"256"]],"b":10},"y":{"s":"log","lim":[12.4632779334,5321.24757663],"inv":false,"g":0,"tk":[[16,"16"],[64,"64"],[512,"512"],[4096,"4,096"]],"b":10},"ti":"At 2,048 vertices the bit matrix beats\npacked rows above 63 arcs per vertex","a":[{"k":"line","c":"#fffff8","s":"x","d":[1,64,2,80,4,112,8,176,16,304,32,560,64,1072,128,2096,256,4144],"p":[81.3,352.27,103.84,340.67,126.38,323.17,148.92,299.67,171.46,271.25,194,239.48,216.54,205.71,239.08,170.84,261.62,135.4]},{"k":"line","c":"#c4501b","s":"x","d":[1,64,2,80,4,112,8,176,16,304,32,560,64,1072,128,2096,256,4144],"p":[81.3,352.27,103.84,340.67,126.38,323.17,148.92,299.67,171.46,271.25,194,239.48,216.54,205.71,239.08,170.84,261.62,135.4]},{"k":"line","c":"#fffff8","s":"x","d":[1,16.00390625,2,24.00390625,4,40.00390625,8,72.00390625,16,136.00390625,32,264.00390625,64,520.00390625,128,1032.00390625,256,2056.00390625],"p":[81.3,424.35,103.84,403.27,126.38,376.71,148.92,346.15,171.46,313.07,194,278.58,216.54,243.33,239.08,207.69,261.62,171.84]},{"k":"line","c":"#1d5fa6","s":"x","d":[1,16.00390625,2,24.00390625,4,40.00390625,8,72.00390625,16,136.00390625,32,264.00390625,64,520.00390625,128,1032.00390625,256,2056.00390625],"p":[81.3,424.35,103.84,403.27,126.38,376.71,148.92,346.15,171.46,313.07,194,278.58,216.54,243.33,239.08,207.69,261.62,171.84]},{"k":"line","c":"#fffff8","s":"x","d":[1,512,2,512,4,512,8,512,16,512,32,512,64,512,128,512,256,512],"p":[81.3,244.14,103.84,244.14,126.38,244.14,148.92,244.14,171.46,244.14,194,244.14,216.54,244.14,239.08,244.14,261.62,244.14]},{"k":"line","c":"#5b6b7c","s":"x","d":[1,512,2,512,4,512,8,512,16,512,32,512,64,512,128,512,256,512],"p":[81.3,244.14,103.84,244.14,126.38,244.14,148.92,244.14,171.46,244.14,194,244.14,216.54,244.14,239.08,244.14,261.62,244.14]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"line","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"line","c":"#8c8c84"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#5c5c57"},{"k":"annotation","c":"#c4501b"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#5b6b7c"}],"lg":[]} 1 4 16 29 63 256 Mean out-degree (arcs per vertex); density is degree / 2,048 16 64 512 4,096 list ties at 1.4% rows tie at 3.1% Modeled buffer size (KiB) Adjacency list (both directions) Compressed sparse rows Adjacency matrix At 2,048 vertices the bit matrix beats packed rows above 63 arcs per vertex
{"v":1,"box":[38.4774,94.1597,1043,437.3555],"x":{"s":"linear","lim":[-0.6979,8.6979],"inv":false,"g":0,"t":"Distance from the corner (steps)","tk":[[0,"0"],[1,"1"],[2,"2"],[3,"3"],[4,"4"],[5,"5"],[6,"6"],[7,"7"],[8,"8"]]},"y":{"s":"linear","lim":[0,5.225],"inv":false,"g":0,"tk":[[0,"0"],[1,"1"],[2,"2"],[3,"3"],[4,"4"],[5,"5"]]},"ti":"A 3-cell wall thins the frontier at distances 2–4; all 22 open cells are reached","a":[{"k":"bar","c":"#1d5fa6","s":"x","d":[0,1,1,2,2,2,3,3,4,4,5,4,6,3,7,2,8,1],"p":[113.09,371.67,220,305.99,326.91,305.99,433.83,240.31,540.74,174.62,647.65,174.62,754.56,240.31,861.47,305.99,968.39,371.67]},{"k":"scatter","c":"#5b6b7c","s":"xy","d":[0,1,1,2,2,3,3,4,4,5,5,4,6,3,7,2,8,1],"p":[113.09,371.67,220,305.99,326.91,240.31,433.83,174.62,540.74,108.94,647.65,174.62,754.56,240.31,861.47,305.99,968.39,371.67],"r":4.96},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#fffff8"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#5b6b7c"},{"k":"annotation","c":"#5c5c57"}],"lg":[]} 0 1 2 3 4 5 6 7 8 Distance from the corner (steps) 0 1 2 3 4 5 with the wall open 5 × 5 grid Cells first reached at each distance A 3-cell wall thins the frontier at distances 2–4; all 22 open cells are reached
{"v":1,"box":[38.4774,150.6246,595,437.3555],"x":{"s":"linear","lim":[-0.6979,8.6979],"inv":false,"g":0,"t":"Distance from the corner (steps)","tk":[[0,"0"],[1,"1"],[2,"2"],[3,"3"],[4,"4"],[5,"5"],[6,"6"],[7,"7"],[8,"8"]]},"y":{"s":"linear","lim":[0,5.225],"inv":false,"g":0,"tk":[[0,"0"],[1,"1"],[2,"2"],[3,"3"],[4,"4"],[5,"5"]]},"ti":"A 3-cell wall thins the frontier at\ndistances 2–4; all 22 open cells are\nreached","a":[{"k":"bar","c":"#1d5fa6","s":"x","d":[0,1,1,2,2,2,3,3,4,4,5,4,6,3,7,2,8,1],"p":[79.81,382.48,139.05,327.6,198.28,327.6,257.51,272.73,316.74,217.85,375.97,217.85,435.2,272.73,494.43,327.6,553.66,382.48]},{"k":"scatter","c":"#5b6b7c","s":"xy","d":[0,1,1,2,2,3,3,4,4,5,5,4,6,3,7,2,8,1],"p":[79.81,382.48,139.05,327.6,198.28,272.73,257.51,217.85,316.74,162.97,375.97,217.85,435.2,272.73,494.43,327.6,553.66,382.48],"r":4.96},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#fffff8"},{"k":"annotation","c":"#1d5fa6"},{"k":"annotation","c":"#5b6b7c"},{"k":"annotation","c":"#5c5c57"}],"lg":[]} 0 1 2 3 4 5 6 7 8 Distance from the corner (steps) 0 1 2 3 4 5 with the wall open 5 × 5 grid Cells first reached at each distance A 3-cell wall thins the frontier at distances 2–4; all 22 open cells are reached
  • Dijkstra finds distance 10 / 10 / 10 across packed rows, list, and matrix on the same weighted edges.
  • The storage model counts buffers for fresh, unweighted layouts over 2,048 vertices.
  • Implicit grid BFS finds 22 reachable cells without storing edges.

Hover or focus a chart for exact values. Each change reruns demo.ts against knotkit/graph in your browser; the defaults reproduce the README figure.

ExportReturnsDoes
compressedSparseRowGraphCompressedSparseRowGraphImmutable graph packed as an Int32Array of row offsets and one flat Int32Array of neighbors, plus a flat Float64Array of weights when weighted; a directed graph counts its in-degrees on the first inDegree call and builds its transposed rows on the first forEachPredecessor call.
adjacencyListGraphMutableGraphMutable graph with one sorted row per vertex, each a slot with spare capacity in one shared Int32Array that compacts once edits leave enough dead space, and a reverse row per vertex when directed; the only layout with addVertex, addEdge, and deleteEdge.
adjacencyMatrixGraphAdjacencyMatrixGraphImmutable dense graph with one bit per vertex pair when unweighted or one Float64Array cell per pair when weighted, checked against GRAPH_MAX_MATRIX_BYTES before allocation; it cannot hold parallel edges.
breadthFirstSearchBreadthFirstSearchResultFewest-hops distance, parent, and visit order from one or more sources over any Adjacency, optionally stopping at a target; O(n + m) on compressed-sparse-row and adjacency-list, O(n² / 32 + m) on an unweighted adjacency-matrix and O(n²) on a weighted one, because every reached row's walk costs its degree on compressed-sparse-row and adjacency-list, but O(n / 32 + d) on an unweighted adjacency-matrix and O(n) on a weighted one.
dijkstraDijkstraResultLeast total cost and parent from one or more sources over any Adjacency. Stops once all requested destinations settle, or searches all reachable vertices. Supports a per-edge cost override and checks non-negative costs on every edge walked. Uses knotkit/heap's indexed priority queue, with O((n + m) log n) time on compressed-sparse-row and adjacency-list, plus O(n² / 32) on an unweighted adjacency-matrix and O(n²) on a weighted one for the row walks.
topologicalOrderTopologicalOrderResultKahn's algorithm over a directed Adjacency, returning an order or one directed cycle as a result rather than a throw; O(n + m) on compressed-sparse-row and adjacency-list, O(n² / 32 + m) on an unweighted adjacency-matrix and O(n²) on a weighted one, because it walks every row.
connectedComponentsConnectedComponentsResultComponent count and a label per vertex for an undirected Adjacency, labels numbered by each component's smallest vertex, every isolated or closed grid cell a component of its own; O(n + m) on compressed-sparse-row and adjacency-list, O(n² / 32 + m) on an unweighted adjacency-matrix and O(n²) on a weighted one.
floydWarshallFloydWarshallResultEvery pairwise shortest distance as a row-major n × n Float64Array, or a vertex on a negative cycle; runs on every layout and allocates its own 8n²-byte matrix, so it does not decide the storage; O(n³) time plus one walk of every row, and a Bellman-Ford pass over the rows when a cycle is negative.
pathInt32Array | undefinedThe vertices from a source to a target, read back from a breadthFirstSearch or dijkstra result; O(path length).
gridAdjacencyGridAdjacencyAn Adjacency over a rows × columns board with 4 or 8 moves per cell, closed cells, and refused moves, computed on demand rather than stored.

Cost per member. Open a row for every operation.

compressedSparseRowGraph 8 members
MemberCost
buildO(n + m)
hasEdgeO(log d)
outDegreeO(1)
inDegreeO(1) after a lazy O(n + m) count into 4n bytes when directed
forEachNeighborO(d)
forEachPredecessorO(d) after a lazy O(n + m) transpose when directed
neighborsO(d)
edgesO(n + m)
adjacencyListGraph 11 members
MemberCost
buildO(n + m)
hasEdgeO(log d)
outDegreeO(1)
inDegreeO(1)
forEachNeighborO(d)
forEachPredecessorO(d)
neighborsO(d)
edgesO(n + m)
addVertexO(1) amortized
addEdgeO(log d + d) amortized
deleteEdgeO(log d + d) amortized
adjacencyMatrixGraph 8 members
MemberCost
buildO(n² / 32 + m), O(n²) weighted
hasEdgeO(1)
outDegreeO(1)
inDegreeO(1)
forEachNeighborO(n / 32 + d), O(n) weighted
forEachPredecessorO(n) when directed
neighborsO(n / 32 + d), O(n) weighted
edgesO(n² / 32 + m)

Every error this module throws is GraphInvalidInputError or GraphParseError, with a code from a closed, exported list. Branch on the code; the message is for people.

GraphInvalidInputError
INVALID_VERTEX_COUNT INVALID_VERTEX INVALID_EDGE INVALID_WEIGHT MISSING_WEIGHT UNEXPECTED_WEIGHT INVALID_FLAG SELF_LOOP PARALLEL_EDGE PARALLEL_EDGES_UNSUPPORTED NEGATIVE_WEIGHT DIRECTED_GRAPH_REQUIRED UNDIRECTED_GRAPH_REQUIRED INVALID_GRID MAX_CAPACITY_EXCEEDED MODIFIED_DURING_ITERATION
GraphParseError
FOREIGN_GRAPH SERIALIZATION_LIMIT_EXCEEDED INVALID_PACKAGE_HEADER UNKNOWN_KIND INVALID_EDGE_SEQUENCE INVALID_GRAPH_FLAGS INVALID_MAGIC UNSUPPORTED_ENVELOPE_VERSION UNSUPPORTED_PAYLOAD_VERSION INVALID_SECTION_GEOMETRY NONZERO_PADDING MISALIGNED_SECTION TRUNCATED_PAYLOAD INVALID_CODEC_RESULT DECODE_BUDGET_EXCEEDED UNSTABLE_BUFFER WRONG_FORMAT INTEGRITY_MISMATCH

Serialization lives in a separate entrypoint, knotkit/graph/wire, so code that never saves a structure never loads a parser.

Functions
serializeGraph, deserializeGraph
Formats
binary
Compatibility
schema-versioned, envelope v1
If you need to…Use instead
merge groups and ask whether two items are connected, without keeping the edgesknotkit/disjoint-set
a visited flag per vertex you already index by numbera pre-sized Uint8Array
a graph keyed by strings with attributes on every node and edge, or a format such as GraphMLgraphology
maximum flow, matching, minimum spanning trees, or strongly connected componentsEffect's Graph module, until a caller moves one of them here
an ordered frontier of your own, such as A* with a heuristicknotkit/heap

Measured by the suite in packages/graph/__tests__/bench. The numbers come from one machine, so run the suite on yours before deciding on speed alone. Compare the recorded timings.

Prompt · knotkit/graph
Use knotkit/graph for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/graph'.

Exports:
- `compressedSparseRowGraph` → `CompressedSparseRowGraph`: Immutable graph packed as an Int32Array of row offsets and one flat Int32Array of neighbors, plus a flat Float64Array of weights when weighted; a directed graph counts its in-degrees on the first inDegree call and builds its transposed rows on the first forEachPredecessor call.
- `adjacencyListGraph` → `MutableGraph`: Mutable graph with one sorted row per vertex, each a slot with spare capacity in one shared Int32Array that compacts once edits leave enough dead space, and a reverse row per vertex when directed; the only layout with addVertex, addEdge, and deleteEdge.
- `adjacencyMatrixGraph` → `AdjacencyMatrixGraph`: Immutable dense graph with one bit per vertex pair when unweighted or one Float64Array cell per pair when weighted, checked against GRAPH_MAX_MATRIX_BYTES before allocation; it cannot hold parallel edges.
- `breadthFirstSearch` → `BreadthFirstSearchResult`: Fewest-hops distance, parent, and visit order from one or more sources over any Adjacency, optionally stopping at a target; O(n + m) on compressed-sparse-row and adjacency-list, O(n² / 32 + m) on an unweighted adjacency-matrix and O(n²) on a weighted one, because every reached row's walk costs its degree on compressed-sparse-row and adjacency-list, but O(n / 32 + d) on an unweighted adjacency-matrix and O(n) on a weighted one.
- `dijkstra` → `DijkstraResult`: Least total cost and parent from one or more sources over any Adjacency. Stops once all requested destinations settle, or searches all reachable vertices. Supports a per-edge cost override and checks non-negative costs on every edge walked. Uses knotkit/heap's indexed priority queue, with O((n + m) log n) time on compressed-sparse-row and adjacency-list, plus O(n² / 32) on an unweighted adjacency-matrix and O(n²) on a weighted one for the row walks.
- `topologicalOrder` → `TopologicalOrderResult`: Kahn's algorithm over a directed Adjacency, returning an order or one directed cycle as a result rather than a throw; O(n + m) on compressed-sparse-row and adjacency-list, O(n² / 32 + m) on an unweighted adjacency-matrix and O(n²) on a weighted one, because it walks every row.
- `connectedComponents` → `ConnectedComponentsResult`: Component count and a label per vertex for an undirected Adjacency, labels numbered by each component's smallest vertex, every isolated or closed grid cell a component of its own; O(n + m) on compressed-sparse-row and adjacency-list, O(n² / 32 + m) on an unweighted adjacency-matrix and O(n²) on a weighted one.
- `floydWarshall` → `FloydWarshallResult`: Every pairwise shortest distance as a row-major n × n Float64Array, or a vertex on a negative cycle; runs on every layout and allocates its own 8n²-byte matrix, so it does not decide the storage; O(n³) time plus one walk of every row, and a Bellman-Ford pass over the rows when a cycle is negative.
- `path` → `Int32Array | undefined`: The vertices from a source to a target, read back from a breadthFirstSearch or dijkstra result; O(path length).
- `gridAdjacency` → `GridAdjacency`: An Adjacency over a rows × columns board with 4 or 8 moves per cell, closed cells, and refused moves, computed on demand rather than stored.

Pick the layout by these rules:
- `compressedSparseRowGraph` (kind 'compressed-sparse-row') when the edge set is known when you build the graph, whatever its density
- `adjacencyListGraph` (kind 'adjacency-list') when edges or vertices arrive after the graph is built
- `adjacencyMatrixGraph` (kind 'adjacency-matrix') when no vertex pair repeats an edge, at least 5% of vertex pairs are edges, you probe hasEdge, and n² / 8 bytes (8n² weighted) fit in 256 MiB

Use something else when:
- merge groups and ask whether two items are connected, without keeping the edges → knotkit/disjoint-set
- a visited flag per vertex you already index by number → a pre-sized Uint8Array
- a graph keyed by strings with attributes on every node and edge, or a format such as GraphML → graphology
- maximum flow, matching, minimum spanning trees, or strongly connected components → Effect's Graph module, until a caller moves one of them here
- an ordered frontier of your own, such as A* with a heuristic → knotkit/heap

Errors are GraphInvalidInputError or GraphParseError with a `code` property. Branch on `error.code`, never on the message. Save and load through `knotkit/graph/wire` (serializeGraph, deserializeGraph).

Full page: https://knotkit.jkomyno.dev/modules/graph.md
Types: node_modules/knotkit/graph/ and https://knotkit.jkomyno.dev/reference/knotkit/graph/