Connected Groups (BFS)

Problem Count the number of connected groups (components) in a grid or graph — Number-of-Islands-shaped, but expect twists such as diagonal adjacency, wrap-around edges, values beyond 0/1, or large sparse inputs.

Input / Output

  • Input: a grid (or adjacency data) marking cells/nodes as land/related or not.
  • Output: the number of connected components.

Constraints

  • Up to 10^3 × 10^3 grid; O(cells) expected.
  • Confirm the adjacency definition (4- vs 8-directional, wrap-around) before coding — it changes the answer. Deeply snake-shaped components can overflow recursion, so an iterative traversal is safer.

Example

  • [[1,1,0],[0,1,0],[0,0,1]] → 2 with 4-adjacency, but 1 with 8-adjacency — which is why adjacency is the first clarifying question.
asked …
LeaderboardSalaryAccount