multiSourceBfsDistances function

List<int> multiSourceBfsDistances(
  1. Adjacency graph,
  2. Iterable<int> sources
)

Hop distance from each node to the nearest of sources.

Index i holds the fewest edges between node i and any seed in sources. Nodes that cannot be reached from any seed are marked with the sentinel -1 (a valid distance is always >= 0). A node that is itself a source has distance 0. Out-of-range source indices are ignored.

Example:

final Adjacency g = buildGraph([(0, 1), (1, 2), (3, 4)], 5);
multiSourceBfsDistances(g, [0, 3]); // [0, 1, 2, 0, 1]

Audited: 2026-06-12 11:26 EDT

Implementation

List<int> multiSourceBfsDistances(Adjacency graph, Iterable<int> sources) {
  // Distances are the first element of the (dist, nearest) pair; the nearest
  // bookkeeping is computed regardless but discarded here to keep callers that
  // only want distances from depending on the richer return shape.
  final (List<int> dist, List<int> _) = multiSourceBfsNearest(graph, sources);
  return dist;
}