#!/usr/bin/python3 """Count the Manhattan-connected regions of 1s in a grid with flood fill.""" def grid1(): return [[1, 0, 1], [1, 1, 0], [0, 0, 0], [1, 1, 1]] def nuke(grid, house): stack = [house] while stack: x, y = stack.pop() #print(x, y) if not grid[y][x]: continue grid[y][x] = 0 for nx in [x-1, x+1]: if 0 <= nx < len(grid[0]): stack.append((nx, y)) for ny in [y-1, y+1]: if 0 <= ny < len(grid): stack.append((x, ny)) def print_grid(grid): for row in grid: print(' '.join(map(str, row))) def count_houses(grid): n = 0 for y in range(len(grid)): for x in range(len(grid[0])): if not grid[y][x]: continue n += 1 print_grid(grid) nuke(grid, (x, y)) return n if __name__ == '__main__': #import cgitb; cgitb.enable(format='text') grid = grid1() print(count_houses(grid))