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
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.
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
constresult=topologicalOrder(dependencies)
if (result.acyclic) build(result.order)
elsereport(result.cycle)
topologicalOrder } from'knotkit/graph'
// [course, prerequisite] pairs: each edge runs prerequisite -> course.
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
constgraph=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.
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.
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.
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
constresult=topologicalOrder(dependencies)
if (result.acyclic) build(result.order)
elsereport(result.cycle)
topologicalOrder(
constcourses:CompressedSparseRowGraph
courses)
if (
constresult:TopologicalOrderResult
result.
acyclic: boolean
acyclic)
constresult: {
readonlyacyclic:true;
readonlyorder:Int32Array;
}
result.
order: Int32Array<ArrayBufferLike>
Every vertex, each after all of its predecessors.
order// Int32Array [0, 1, 2, 3]
else
constresult: {
readonlyacyclic:false;
readonlycycle: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.
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.
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.
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
constgraph=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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
distance[3] // hops from vertex 0 to vertex 3, or -1
breadthFirstSearch, type
(alias) interfaceAdjacency
importAdjacency
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.
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
constladder:Adjacency
ladder:
(alias) interfaceAdjacency
importAdjacency
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:
constwords: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.
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<
constwords: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.
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.
new <string, number>(iterable?:Iterable<readonly [string, number]> |null|undefined) =>Map<string, number> (+3 overloads)
Map<string, number>()
const
constid: (key:string) =>number
id= (
key: string
key:string) =>
constids: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.
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
the edge set is known when you build the graph, whatever its density
4(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 built
12n + 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 MiB
n² / 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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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/