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?- A. 5
- B. 3
- C. 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
- Problem: In an unweighted graph, find the shortest distance from node 0 to node 5 and the NUMBER of distinct shortest paths. python from…
- A Floyd–Warshall implementation writes its loops as for i … for j … for k (k innermost) instead of k outermost, and runs the triple loop…
- Problem: Build a minimum spanning tree with Kruskal's algorithm and report its total weight. python edges =…
- Problem: A CPU runs tasks (letters); identical tasks need at least n idle-or-other slots between them. Find the minimum total time slots…
- Problem: Children stand in a line with ratings; each gets ≥ 1 candy and a child with a higher rating than a NEIGHBOUR must get more than…
- Problem: Count the ways to make amount 5 from coins [1, 2, 5]. A developer wrote the loops in this order. python def ways(coins, amt): dp…