Data Structures & AlgorithmsHardInfosys SP/DSE · Product Company SDE
Problem: A 'closed island' is a group of 0-cells (land) connected 4-directionally that does NOT touch the grid border. Count them.
Problem: A 'closed island' is a group of 0-cells (land) connected 4-directionally that does NOT touch the grid border. Count them.
def closed(grid):
R, C = len(grid), len(grid[0]); g = [row[:] for row in grid]
def sink(i, j):
st = [(i, j)]; ok = True
while st:
i, j = st.pop()
if not (0 <= i < R and 0 <= j < C): ok = False; continue
if g[i][j] != 0: continue
g[i][j] = 1
st += [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]
return ok
return sum(sink(i, j) for i in range(R) for j in range(C) if g[i][j] == 0)
grid = [[1, 1, 1, 1, 0, 1],
[1, 0, 0, 1, 0, 1],
[1, 0, 1, 1, 1, 1],
[1, 1, 1, 0, 1, 1],
[0, 1, 1, 1, 1, 0]]
print(closed(grid))What is printed?- A. 3
- B. 1
- C. 5
- D. 2
Correct answer: D. 2
Flood each 0-region once; it is closed only if the flood never steps outside the grid. Regions: {(1,1), (1,2), (2,1)} closed; {(3,3)} closed; {(0,4), (1,4)} touches the top border; (4,0) and (4,5) lie on the border. → 2. The whole region must be flooded even after it is known to be open, otherwise its remaining cells would be counted again later. O(R·C).
More Coding Interview Problems questions
- Problem: On a board of 'X' and 'O', capture every 'O' region not connected to the border by turning it into 'X'. Mark border-connected…
- Problem: Run Bellman–Ford from node 0 on a directed graph with negative edges, then check for a negative cycle with one more relaxation…
- Problem: All-pairs shortest paths with Floyd–Warshall on a 4-node directed graph (INF = no path). python INF = float("inf") def floyd(n…
- Problem: n computers and a list of cables; you may unplug any cable and reconnect it between any two computers. Minimum moves to connect…
- Problem: Given equations like "a==b" and "b!=c" over single-letter variables, can all hold at once? Union all '==' pairs first, then check…
- Problem: A 3-wheel lock starts at "000"; each move turns one wheel by ±1 (9 wraps to 0). Some codes are dead (the lock jams). Find the…