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?
  1. A. 3
  2. B. 1
  3. C. 5
  4. 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

Exams that ask this topic