# dijkstra

> **dijkstra**(`adjacency`, `options`): [`DijkstraResult`](/reference/knotkit/graph/interfaces/dijkstraresult/)

Defined in: [packages/graph/src/dijkstra.ts:92](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/dijkstra.ts#L92)

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.

## Parameters

### adjacency

[`Adjacency`](/reference/knotkit/graph/interfaces/adjacency/)

### options

[`DijkstraOptions`](/reference/knotkit/graph/interfaces/dijkstraoptions/)

## Returns

[`DijkstraResult`](/reference/knotkit/graph/interfaces/dijkstraresult/)

## Throws

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

```ts
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]
```
