Depth-first search on a graph
Leave trees for a general graph, like a grid, and two things change. A cell can be reached by more than one route, and routes can loop. So the seen-set comes back, for the same reason as in breadth-first search: without it, a walk goes round a loop forever.
On a graph the same walk is depth-first search, DFS for short. It reaches every cell connected to the start once, in time for rows and columns, the same as BFS.
SIDES = ((-1, 0), (1, 0), (0, -1), (0, 1))
def open_neighbors(grid, r, c):
found = []
for dr, dc in SIDES:
nr, nc = r + dr, c + dc
if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] != "#":
found.append((nr, nc))
return found
print(open_neighbors(["..#...", "..#.##", "###...", ".#..#."], 0, 1))
[(1, 1), (0, 0)]
open_neighbors is the one from the grid BFS lesson. Counting the regions takes a scan and a search. Scan every cell, row by row, and skip walls and cells already in seen. Any other cell is one no earlier search reached, so it starts a new region: add 1 to the count, mark the cell, and push it on a stack. Then pop cells until the stack is empty, and push each open neighbor that isn't in seen yet, marking it as you push.
That's the grid BFS search with stack.pop() where it had queue.popleft().
The grid is ["..#...", "..#.##", "###...", ".#..#."], with # a wall. How many regions of open cells?