# breadthFirstSearch

> **breadthFirstSearch**(`adjacency`, `options`): [`BreadthFirstSearchResult`](/reference/knotkit/graph/interfaces/breadthfirstsearchresult/)

Defined in: [packages/graph/src/breadth-first-search.ts:46](https://github.com/jkomyno/knotkit/blob/ef04dc6fd5182dca281abddf3e1dcb13118c15a4/packages/graph/src/breadth-first-search.ts#L46)

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.

## Parameters

### adjacency

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

### options

[`BreadthFirstSearchOptions`](/reference/knotkit/graph/interfaces/breadthfirstsearchoptions/)

## Returns

[`BreadthFirstSearchResult`](/reference/knotkit/graph/interfaces/breadthfirstsearchresult/)

## Throws

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

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