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?- A. 3
- B. 2
- C. 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
- Problem: How many subarrays of [1, -1, 2, -2, 3, -3] have sum zero? Run the prefix-count code. python from collections import Counter a =…
- Problem: A data stream needs the median of the last k elements. Which structure supports each slide in O(log k) time?
- Problem: Consider a connected undirected graph whose edge weights are all distinct. Which statement is true?
- Problem: What is the standard time complexity of bitmask DP for the travelling salesman problem on n cities?
- Array a = [3, -1, 2, 6, -4, 5, 1, -2]. How many non-empty contiguous subarrays have a sum divisible by 4?
- Binary array a = [1, 0, 1, 1, 0, 0, 1, 0, 1]. How many contiguous subarrays have exactly two 1s?