This algorithm uses a depth-first search to traverse through the grid, marking visited cells to avoid double-counting. It counts the number of houses based on the clusters of connected cells with the value 1.
def count_houses(grid):
def dfs(i, j):
if i < 0 or i >= rows or j < 0 or j >= cols or grid[i][j] == 0:
return
grid[i][j] = 0 # Mark the cell as visited
for x, y in directions:
dfs(i + x, j + y)
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
house_count = 0
for i in range(rows):
for j in range(cols):
if grid[i][j] == 1:
house_count += 1
dfs(i, j)
return house_count
# Example Usage:
grid = [
[1, 0, 1, 0, 0],
[1, 1, 1, 0, 1],
[0, 0, 0, 1, 0],
[1, 1, 1, 0, 0],
]
result = count_houses(grid)
print(f'Total number of houses: {result}')