Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE

Problem: Count islands (groups of '1' cells connected up, down, left or right) on a satellite grid.

Problem: Count islands (groups of '1' cells connected up, down, left or right) on a satellite grid.
def islands(g):
    R, C = len(g), len(g[0]); seen = set(); n = 0
    def dfs(r, c):
        if not (0 <= r < R and 0 <= c < C) or g[r][c] != '1' or (r, c) in seen: return
        seen.add((r, c))
        for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): dfs(r + dr, c + dc)
    for r in range(R):
        for c in range(C):
            if g[r][c] == '1' and (r, c) not in seen:
                n += 1; dfs(r, c)
    return n
print(islands(["11000", "01001", "10011", "00000", "10101"]))
What is printed?
  1. A. 5
  2. B. 10
  3. C. 6
  4. D. 3

Correct answer: C. 6

Each unvisited land cell starts a DFS that marks its whole island: {(0,0),(0,1),(1,1)}, {(1,4),(2,3),(2,4)}, {(2,0)} and three single cells in the last row → 6. Allowing diagonal moves merges (1,1) with (2,0) and gives 5; counting land cells gives 10; a loop bound of range(R − 1) skips the last row and gives 3.

More Coding Interview Problems questions

Exams that ask this topic