Skip to content

breadthFirstSearch(adjacency, options): BreadthFirstSearchResult

Defined in: packages/graph/src/breadth-first-search.ts:46

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.

Adjacency

BreadthFirstSearchOptions

BreadthFirstSearchResult

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.

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