Count Sub Islands (LeetCode 1905): Solution and Explanation

Medium
Array
Depth First Search
Breadth First Search
Union Find
Matrix

Given two binary grids of the same size, count the islands of grid2 whose every cell is also land in grid1.

Intuition

This is Number of Islands with one extra question per island: does any of its cells sit on water in grid1?

A flood fill already touches every cell of an island exactly once, so the check costs nothing extra. Look at grid1[r][c] each time a cell is visited and remember if it was ever 0.

The one trap is stopping early. If you abandon the flood as soon as you see grid1 water, the rest of that island stays unvisited and is later counted as a separate island. Finish the flood, then decide.

Approach: Flood fill with a sub-island flag

  1. Scan grid2 cell by cell. Skip water and cells already sunk.
  2. On fresh land, set it to 0, push it on a stack, and set isSub = true.
  3. Pop a cell. If grid1 is 0 there, set isSub = false. Push each in-bounds neighbor that is still land in grid2, sinking it as you push.
  4. When the stack empties, the whole island is sunk. Add 1 to the answer if isSub is still true.
  5. Return the count after the scan.

Step-by-step example

grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]
  1. The flood from (0,0) covers (0,0), (0,1), (0,2), (1,2), (1,3), (1,4). grid1 is land under all six, so count = 1.
  2. The flood from (2,1) covers only (2,1). grid1[2][1] is water, so this island does not count.
  3. (3,0) is a single cell on grid1 land, so count = 2.
  4. The flood from (3,2) covers (3,2), (3,3), (4,3). grid1[3][2] is water, so it does not count.
  5. (4,1) is a single cell on grid1 land, so count = 3. The answer is 3.

Code: Python, Java, C++

1class Solution:
2    def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:
3        m, n = len(grid2), len(grid2[0])
4        count = 0
5        for i in range(m):
6            for j in range(n):
7                if grid2[i][j] != 1:
8                    continue
9                grid2[i][j] = 0
10                stack = [(i, j)]
11                isSub = True
12                while stack:
13                    r, c = stack.pop()
14                    if grid1[r][c] == 0:
15                        isSub = False
16                    for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
17                        if 0 <= nr < m and 0 <= nc < n and grid2[nr][nc] == 1:
18                            grid2[nr][nc] = 0
19                            stack.append((nr, nc))
20                if isSub:
21                    count += 1
22        return count
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m * n)

Each cell of grid2 is pushed and popped at most once, and the scan visits every cell once.

Space

O(m * n)

The flood stack can hold a large fraction of the grid when one island covers most of it. grid2 is reused as the visited marker.

Other approaches

Sink the bad islands first (time O(m * n), space O(m * n))

First flood away every grid2 island that has a cell where grid2 is 1 and grid1 is 0. Then count the islands left in grid2 with a plain Number of Islands pass. Same cost, two passes.

Union-find (time O(m * n * α(m * n)), space O(m * n))

Union adjacent land cells of grid2, mark a root as bad if any member sits on grid1 water, then count good roots. Works, but more code than a flood fill.

Common mistakes

  • Returning from the flood as soon as grid1 water is found. The unvisited part of the island is later counted as a new island.
  • Using isSub = isSub and dfs(...) with short-circuit evaluation. Once isSub is false the recursive call is skipped and the island is only partly sunk; call dfs first, then combine.
  • Marking a cell visited when it is popped instead of when it is pushed. The same cell can then be pushed many times.
  • Deep recursion. A 500 x 500 island makes a recursive DFS 250,000 levels deep, which overflows Python's default stack; an explicit stack avoids it.

Frequently asked questions

Do I need to find the islands of grid1 at all?

No. A grid2 island is a sub-island exactly when every one of its cells is land in grid1. Since the grid2 island is connected, those cells automatically lie inside a single grid1 island.

Is it okay to modify grid2?

Yes for this problem. Setting visited cells to 0 avoids a separate visited array. If the caller needs grid2 later, copy it first.

BFS or DFS?

Either. The order in which cells of an island are visited does not change whether one of them sits on grid1 water.