Algorithms · Level 2 Graphs

Counting Regions with DFS

Count the separate zones of a floor map with depth-first search and your own stack, so a long corridor doesn't hit Python's recursion limit.

  • start a search from each unvisited cell
  • a stack is last in, first out
  • recursion stops at about 1,000 levels

Depth-first search follows one path as far as it goes, then backs up. To count regions, start a search from each unvisited cell and mark everything it reaches. Trap: recursion stops at about 1,000 levels; use your own stack.

stack, seen = [start], {start}
while stack:
    cell = stack.pop()  # last in, first out
    for nxt in neighbours(cell):
        if nxt not in seen:
            seen.add(nxt)
            stack.append(nxt)

Write count_regions(grid): the number of separate groups of # cells, where cells touch up, down, left or right (not diagonally). Example: count_regions(['##.', '..#']) → 2.

solution.py
Test Suites Pending
Output