Predict the output
What does this print?
steps = ((1, 0), (-1, 0), (0, 1), (0, -1))
grid = ["##.", ".#.", "..#"]
seen = set()
sizes = []
for r in range(3):
for c in range(3):
if grid[r][c] == "#" and (r, c) not in seen:
seen.add((r, c))
todo, size = [(r, c)], 0
while todo:
y, x = todo.pop()
size += 1
for dy, dx in steps:
ny, nx = y + dy, x + dx
if (0 <= ny < 3 and 0 <= nx < 3
and grid[ny][nx] == "#"
and (ny, nx) not in seen):
seen.add((ny, nx))
todo.append((ny, nx))
sizes.append(size)
print(sizes)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A [3, 1]
Right: the top three cells join; the corner cell is alone.
Diagonal contact does not join patches, so the bottom-right cell stays separate.
Why not the others?
- B [4]. (2, 2) only touches (1, 2) and (2, 1), which are water.
- C [2, 1, 1]. (1, 1) touches (0, 1), so three cells form one patch.