Data Structures & AlgorithmsModerateTCS NQT · graph warm-up

Problem: How many islands (4-connected groups of '1') are in the grid below? Run the DFS code.

Problem: How many islands (4-connected groups of '1') are in the grid below? Run the DFS code.
g = ['11000', '11000', '00100', '00011']
n, m = len(g), len(g[0])
seen = [[False] * m for _ in range(n)]
def dfs(i, j):
    seen[i][j] = True
    for di, dj in ((1, 0), (-1, 0), (0, 1), (0, -1)):
        a, b = i + di, j + dj
        if 0 <= a < n and 0 <= b < m and g[a][b] == '1' and not seen[a][b]:
            dfs(a, b)
islands = 0
for i in range(n):
    for j in range(m):
        if g[i][j] == '1' and not seen[i][j]:
            islands += 1
            dfs(i, j)
print(islands)
What is printed?
  1. A. 3
  2. B. 2
  3. C. 4
  4. D. 5

Correct answer: A. 3

The top-left 2x2 block is one island, the centre cell is a second, and the bottom-right pair is a third. Diagonal-only neighbours are not joined under 4-connectivity.

More Coding Interview Problems questions

Exams that ask this topic