A matrix of characters or of zeros and ones often represents a map. Typical questions are how many connected regions there are, or which is the largest. They are solved with a flood fill: from one square you visit everything connected, marking it so you do not repeat.
def flood(g, i, j):
"""Marks as visited (with '#') the whole region of '.' connected to (i, j)."""
stack = [(i, j)]
g[i][j] = "#"
while stack:
x, y = stack.pop()
for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nx, ny = x + dx, y + dy
if 0 <= nx < len(g) and 0 <= ny < len(g[0]) and g[nx][ny] == ".":
g[nx][ny] = "#"
stack.append((nx, ny))
board = ["..X..",
".XX..",
"XX..X"]
g = [list(row) for row in board]
regions = 0
for i in range(len(g)):
for j in range(len(g[0])):
if g[i][j] == ".":
regions += 1
flood(g, i, j)
print(regions) # 2
- A stack (depth-first) or a queue
collections.deque(breadth-first) is used; the result of counting regions is the same. - Mark squares when adding them to the stack, not when taking them out: that way they never enter twice.
- If you want to actually change the squares (as in an image editor), paint instead of marking; if you do not want to modify the original map, work on a copy or use a
visitedset. - The cost is O(r·c): each square is visited once.
You practice it in Paint bucket.