ProgrammingVery hardCodeforces-style · placement coding round

What is printed?

What is printed?
from collections import deque
def islands(g):
    R, C = len(g), len(g[0])
    seen = set()
    cnt = 0
    for r in range(R):
        for c in range(C):
            if g[r][c] == '1' and (r, c) not in seen:
                cnt += 1
                q = deque([(r, c)])
                seen.add((r, c))
                while q:
                    x, y = q.popleft()
                    for nx, ny in ((x+1, y), (x-1, y), (x, y+1), (x, y-1)):
                        if 0 <= nx < R and 0 <= ny < C and g[nx][ny] == '1' and (nx, ny) not in seen:
                            seen.add((nx, ny))
                            q.append((nx, ny))
    return cnt
print(islands(['11000', '11011', '00100', '00011']))
  1. A. 3
  2. B. 5
  3. C. 2
  4. D. 4

Correct answer: D. 4

Each BFS from an unseen land cell finds one whole island. The lone cell at (2,2) touches no other land, so the four islands are the top-left block, the pair in row 1, the single cell and the pair in row 3.

More Python Programming questions

Exams that ask this topic