Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Count islands in a grid of 1s (land) and 0s where land cells touching even DIAGONALLY belong to the same island.

Problem: Count islands in a grid of 1s (land) and 0s where land cells touching even DIAGONALLY belong to the same island.
g = [[1,0,0,1],
     [0,1,0,1],
     [0,0,0,0],
     [1,0,1,1]]
R, Cc = len(g), len(g[0]); seen = set()
def dfs(r, c):
    seen.add((r, c))
    for dr in (-1, 0, 1):
        for dc in (-1, 0, 1):
            x, y = r + dr, c + dc
            if 0 <= x < R and 0 <= y < Cc and g[x][y] and (x, y) not in seen:
                dfs(x, y)
cnt = 0
for r in range(R):
    for c in range(Cc):
        if g[r][c] and (r, c) not in seen:
            cnt += 1; dfs(r, c)
print(cnt)
What is printed?
  1. A. 5
  2. B. 3
  3. C. 4
  4. D. 6

Correct answer: C. 4

With 4-direction moves there are 5 islands, but (0,0) and (1,1) touch diagonally and merge, giving 4: {(0,0),(1,1)}, {(0,3),(1,3)}, {(3,0)} and {(3,2),(3,3)}.

More Coding Interview Problems questions

Exams that ask this topic