# 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

## Use

```ts
import { compressedSparseRowGraph, topologicalOrder } from 'knotkit/graph'

// [course, prerequisite] pairs: each edge runs prerequisite -> course.
const prerequisites = [
  [1, 0],
  [2, 0],
  [3, 1],
  [3, 2],
] as const
const courses = compressedSparseRowGraph({
  vertexCount: 4,
  directed: true,
  weighted: false,
  edges: prerequisites.map(([course, before]) => [before, course] as const),
})

const result = topologicalOrder(courses)
if (result.acyclic) result.order // Int32Array [0, 1, 2, 3]
else result.cycle // the courses that wait on each other
```

```ts
import { compressedSparseRowGraph, dijkstra, path } from 'knotkit/graph'

const times = [
  [2, 1, 1],
  [2, 3, 1],
  [3, 4, 1],
] as const
const network = compressedSparseRowGraph({ vertexCount: 5, directed: true, weighted: true, edges: times })

const delays = dijkstra(network, { sources: [2] })
delays.distance // Float64Array [Infinity, 1, 0, 1, 2]
path(delays, 4) // Int32Array [2, 3, 4]
```

```ts
import { breadthFirstSearch, connectedComponents, gridAdjacency } from 'knotkit/graph'

const grid = [
  [2, 1, 1],
  [1, 1, 0],
  [0, 1, 1],
]
const board = gridAdjacency({ rows: 3, columns: 3, open: (cell) => grid[Math.floor(cell / 3)][cell % 3] !== 0 })

const { distance } = breadthFirstSearch(board, { sources: [board.cell(0, 0)] })
Math.max(...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 { component } = connectedComponents(board)
const patches = new Set<number>()
for (let cell = 0; cell < board.vertexCount; cell += 1)
  if (grid[Math.floor(cell / 3)][cell % 3] !== 0) patches.add(component[cell])
patches.size // 1 patch of oranges; connectedComponents(board).count is 3, counting each empty cell
```

```ts
import { adjacencyListGraph } from 'knotkit/graph'

const roads = adjacencyListGraph({ vertexCount: 2, directed: false, weighted: true })
const town = roads.addVertex() // 2
roads.addEdge(0, town, 7) // true
roads.addEdge(town, 0, 7) // false: the same road, already stored
roads.deleteEdge(0, town) // true
```

```ts
import { breadthFirstSearch, type Adjacency } from 'knotkit/graph'

const words = ['hot', 'dot', 'dog', 'cog', 'lot', 'log']
const oneLetterApart = (a: string, b: string) => [...a].filter((letter, index) => letter !== b[index]).length === 1
const ladder: Adjacency = {
  vertexCount: words.length,
  directed: false,
  forEachNeighbor: (word, visit) => {
    for (let other = 0; other < words.length; other += 1) if (oneLetterApart(words[word], words[other])) visit(other, 1)
  },
}

breadthFirstSearch(ladder, { sources: [0] }).distance[3] // 3 steps from "hot" to "cog"
```

```ts
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(),
})
```

```ts
const ids = new Map<string, number>()
const id = (key: string) => ids.get(key) ?? (ids.set(key, ids.size), ids.size - 1)
```

## What it solves

* 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

## Choose a layout

| Factory                                                | Choose when                                                                                                                              | Cost                                                                                                                                                                                                                                                                                                                                                                                                                              |
| ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `compressedSparseRowGraph`kind `compressed-sparse-row` | 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                                                                                                                                                                                                     |

[Performance and benchmarks for this module](https://github.com/jkomyno/knotkit/blob/main/packages/graph/README.md#performance)

## Worked example

Vertices2,04811Reset

* 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`](https://github.com/jkomyno/knotkit/blob/main/packages/graph/demo.ts) against `knotkit/graph` in your browser; the defaults reproduce the README figure.

## API

| Export                                                                                     | Returns                     | Does                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| ------------------------------------------------------------------------------------------ | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`compressedSparseRowGraph`](/reference/knotkit/graph/functions/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`](/reference/knotkit/graph/functions/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`](/reference/knotkit/graph/functions/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`](/reference/knotkit/graph/functions/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`](/reference/knotkit/graph/functions/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`](/reference/knotkit/graph/functions/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`](/reference/knotkit/graph/functions/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`](/reference/knotkit/graph/functions/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`](/reference/knotkit/graph/functions/path/)                                         | `Int32Array \| undefined`   | The vertices from a source to a target, read back from a breadthFirstSearch or dijkstra result; O(path length).                                                                                                                                                                                                                                                                                                                                                       |
| [`gridAdjacency`](/reference/knotkit/graph/functions/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.                                                                                                                                                                                                                                                                                                                          |

Cost per member. Open a row for every operation.

`compressedSparseRowGraph` 8 members

| Member               | Cost                                                         |
| -------------------- | ------------------------------------------------------------ |
| `build`              | O(n + m)                                                     |
| `hasEdge`            | O(log d)                                                     |
| `outDegree`          | O(1)                                                         |
| `inDegree`           | O(1) after a lazy O(n + m) count into 4n bytes when directed |
| `forEachNeighbor`    | O(d)                                                         |
| `forEachPredecessor` | O(d) after a lazy O(n + m) transpose when directed           |
| `neighbors`          | O(d)                                                         |
| `edges`              | O(n + m)                                                     |

`adjacencyListGraph` 11 members

| Member               | Cost                   |
| -------------------- | ---------------------- |
| `build`              | O(n + m)               |
| `hasEdge`            | O(log d)               |
| `outDegree`          | O(1)                   |
| `inDegree`           | O(1)                   |
| `forEachNeighbor`    | O(d)                   |
| `forEachPredecessor` | O(d)                   |
| `neighbors`          | O(d)                   |
| `edges`              | O(n + m)               |
| `addVertex`          | O(1) amortized         |
| `addEdge`            | O(log d + d) amortized |
| `deleteEdge`         | O(log d + d) amortized |

`adjacencyMatrixGraph` 8 members

| Member               | Cost                           |
| -------------------- | ------------------------------ |
| `build`              | O(n² / 32 + m), O(n²) weighted |
| `hasEdge`            | O(1)                           |
| `outDegree`          | O(1)                           |
| `inDegree`           | O(1)                           |
| `forEachNeighbor`    | O(n / 32 + d), O(n) weighted   |
| `forEachPredecessor` | O(n) when directed             |
| `neighbors`          | O(n / 32 + d), O(n) weighted   |
| `edges`              | O(n² / 32 + m)                 |

## Errors

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`

## Save and restore

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

## When not to use it

| If you need to…                                                                              | Use instead                                                  |
| -------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
| merge groups and ask whether two items are connected, without keeping the edges              | [`knotkit/disjoint-set`](/modules/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`](/modules/heap/)                             |

## Performance

Measured by the suite in [`packages/graph/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/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](/benchmarks/#graph).

## Prompt an agent

Prompt · knotkit/graphCopy prompt

```
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/
```

## See also

* [API reference](/reference/knotkit/graph/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/graph/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/graph/knotkit.capability.json)suggest a change to the source record
