canReach function

bool canReach(
  1. Adjacency graph,
  2. int from,
  3. int to
)

Whether node to is reachable from node from via one or more edges.

Returns false for out-of-range endpoints. from == to is true only when a genuine path leads back, never trivially, matching reachabilitySets. Audited: 2026-06-12 11:26 EDT

Implementation

bool canReach(Adjacency graph, int from, int to) {
  // Validate endpoints before traversing so an out-of-range query is a clean
  // false rather than a range error inside the BFS.
  if (from < 0 || from >= graph.length) return false;
  if (to < 0 || to >= graph.length) return false;
  return _reachableFrom(graph, from).contains(to);
}