Skip to content

1905. Count Sub Islands

SourceWeekly Contest 246 Q3DifficultyMediumRating1678

Description

You are given two m x n binary matrices grid1 and grid2 containing only 0's (representing water) and 1's (representing land). An island is a group of 1's connected 4-directionally (horizontal or vertical). Any cells outside of the grid are considered water cells.

An island in grid2 is considered a sub-island if there is an island in grid1 that contains all the cells that make up this island in grid2.

Return the number of islands in grid2 that are considered sub-islands.

 

Example 1:

Input: 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]]
Output: 3
Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.

Example 2:

Input: grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]
Output: 2 
Explanation: In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.

 

Constraints:

  • m == grid1.length == grid2.length
  • n == grid1[i].length == grid2[i].length
  • 1 <= m, n <= 500
  • grid1[i][j] and grid2[i][j] are either 0 or 1.

Solutions

Solution 1: DFS

Thinking

Each island of \(\textit{grid2}\) is a sub-island only if every land cell also lies on land in \(\textit{grid1}\). Checking cells in isolation cannot group them by island.

One DFS (or BFS) walks a component, zeros \(\textit{grid2}\) to mark it visited, and ANDs the corresponding \(\textit{grid1}\) cells to decide whether the island is valid.

A linear scan starts a search at every remaining \(1\) in \(\textit{grid2}\) and sums the return values.

We can traverse each cell \((i, j)\) in the matrix grid2. If the value of the cell is \(1\), we start a depth-first search from this cell, set the value of all cells connected to this cell to \(0\), and record whether the corresponding cell in grid1 is also \(1\) for all cells connected to this cell. If it is \(1\), it means that this cell is also an island in grid1, otherwise it is not. Finally, we count the number of sub-islands in grid2.

The time complexity is \(O(m \times n)\), and the space complexity is \(O(m \times n)\). Here, \(m\) and \(n\) are the number of rows and columns of the matrices grid1 and grid2, respectively.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
    def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:
        def dfs(i: int, j: int) -> int:
            ok = grid1[i][j]
            grid2[i][j] = 0
            for a, b in pairwise(dirs):
                x, y = i + a, j + b
                if 0 <= x < m and 0 <= y < n and grid2[x][y] and not dfs(x, y):
                    ok = 0
            return ok

        m, n = len(grid1), len(grid1[0])
        dirs = (-1, 0, 1, 0, -1)
        return sum(dfs(i, j) for i in range(m) for j in range(n) if grid2[i][j])
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
    private final int[] dirs = {-1, 0, 1, 0, -1};
    private int[][] grid1;
    private int[][] grid2;
    private int m;
    private int n;

    public int countSubIslands(int[][] grid1, int[][] grid2) {
        m = grid1.length;
        n = grid1[0].length;
        this.grid1 = grid1;
        this.grid2 = grid2;
        int ans = 0;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid2[i][j] == 1) {
                    ans += dfs(i, j);
                }
            }
        }
        return ans;
    }

    private int dfs(int i, int j) {
        int ok = grid1[i][j];
        grid2[i][j] = 0;
        for (int k = 0; k < 4; ++k) {
            int x = i + dirs[k], y = j + dirs[k + 1];
            if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y] == 1) {
                ok &= dfs(x, y);
            }
        }
        return ok;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
    int countSubIslands(vector<vector<int>>& grid1, vector<vector<int>>& grid2) {
        int m = grid1.size(), n = grid1[0].size();
        int ans = 0;
        int dirs[5] = {-1, 0, 1, 0, -1};
        function<int(int, int)> dfs = [&](int i, int j) {
            int ok = grid1[i][j];
            grid2[i][j] = 0;
            for (int k = 0; k < 4; ++k) {
                int x = i + dirs[k], y = j + dirs[k + 1];
                if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y]) {
                    ok &= dfs(x, y);
                }
            }
            return ok;
        };
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid2[i][j]) {
                    ans += dfs(i, j);
                }
            }
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func countSubIslands(grid1 [][]int, grid2 [][]int) (ans int) {
    m, n := len(grid1), len(grid1[0])
    dirs := [5]int{-1, 0, 1, 0, -1}
    var dfs func(i, j int) int
    dfs = func(i, j int) int {
        ok := grid1[i][j]
        grid2[i][j] = 0
        for k := 0; k < 4; k++ {
            x, y := i+dirs[k], j+dirs[k+1]
            if x >= 0 && x < m && y >= 0 && y < n && grid2[x][y] == 1 && dfs(x, y) == 0 {
                ok = 0
            }
        }
        return ok
    }
    for i := 0; i < m; i++ {
        for j := 0; j < n; j++ {
            if grid2[i][j] == 1 {
                ans += dfs(i, j)
            }
        }
    }
    return
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function countSubIslands(grid1: number[][], grid2: number[][]): number {
    const [m, n] = [grid1.length, grid1[0].length];
    let ans = 0;
    const dirs: number[] = [-1, 0, 1, 0, -1];
    const dfs = (i: number, j: number): number => {
        let ok = grid1[i][j];
        grid2[i][j] = 0;
        for (let k = 0; k < 4; ++k) {
            const [x, y] = [i + dirs[k], j + dirs[k + 1]];
            if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y]) {
                ok &= dfs(x, y);
            }
        }
        return ok;
    };
    for (let i = 0; i < m; ++i) {
        for (let j = 0; j < n; j++) {
            if (grid2[i][j]) {
                ans += dfs(i, j);
            }
        }
    }
    return ans;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function countSubIslands(grid1, grid2) {
    const [m, n] = [grid1.length, grid1[0].length];
    let ans = 0;
    const dirs = [-1, 0, 1, 0, -1];
    const dfs = (i, j) => {
        let ok = grid1[i][j];
        grid2[i][j] = 0;
        for (let k = 0; k < 4; ++k) {
            const [x, y] = [i + dirs[k], j + dirs[k + 1]];
            if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y]) {
                ok &= dfs(x, y);
            }
        }
        return ok;
    };
    for (let i = 0; i < m; ++i) {
        for (let j = 0; j < n; j++) {
            if (grid2[i][j]) {
                ans += dfs(i, j);
            }
        }
    }
    return ans;
}

Solution 2: Explicit Stack

Thinking

An island of \(\textit{grid2}\) is a sub-island only when every land cell is also land in \(\textit{grid1}\). Cells that are not grouped by connectivity cannot be counted as one island.

Recursing along a snake of \(1000\) land cells overflows the call stack, and \(m,n\le 500\) can hold that snake.

The check only has to walk the whole island, zero \(\textit{grid2}\), and AND the matching \(\textit{grid1}\) cells. It does not need a recursive return.

When a remaining \(1\) is found, push it onto an explicit stack. Pop a cell, AND it with \(\textit{grid1}\), and push each neighboring land cell after marking it. The sum of these results is the number of sub-islands.

Scan every cell of grid2. When it is still \(1\), walk that island with an explicit stack, set grid2 to \(0\) along the way, and AND the matching grid1 cells. A result of \(1\) means the island is a sub-island.

The time complexity is \(O(m \times n)\), and the space complexity is \(O(m \times n)\). Here, \(m\) and \(n\) are the number of rows and columns of the matrices grid1 and grid2, respectively.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def countSubIslands(self, grid1: List[List[int]], grid2: List[List[int]]) -> int:
        def flood(i: int, j: int) -> int:
            ok = 1
            grid2[i][j] = 0
            stk = [(i, j)]
            while stk:
                i, j = stk.pop()
                ok &= grid1[i][j]
                for a, b in pairwise(dirs):
                    x, y = i + a, j + b
                    if 0 <= x < m and 0 <= y < n and grid2[x][y]:
                        grid2[x][y] = 0
                        stk.append((x, y))
            return ok

        m, n = len(grid1), len(grid1[0])
        dirs = (-1, 0, 1, 0, -1)
        return sum(flood(i, j) for i in range(m) for j in range(n) if grid2[i][j])
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
    public int countSubIslands(int[][] grid1, int[][] grid2) {
        int m = grid1.length, n = grid1[0].length;
        int ans = 0;
        int[] dirs = {-1, 0, 1, 0, -1};
        Deque<int[]> stk = new ArrayDeque<>();
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid2[i][j] == 1) {
                    ans += flood(grid1, grid2, stk, dirs, i, j);
                }
            }
        }
        return ans;
    }

    private int flood(int[][] grid1, int[][] grid2, Deque<int[]> stk, int[] dirs, int i, int j) {
        int m = grid1.length, n = grid1[0].length;
        int ok = 1;
        grid2[i][j] = 0;
        stk.push(new int[] {i, j});
        while (!stk.isEmpty()) {
            int[] cur = stk.pop();
            i = cur[0];
            j = cur[1];
            ok &= grid1[i][j];
            for (int k = 0; k < 4; ++k) {
                int x = i + dirs[k], y = j + dirs[k + 1];
                if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y] == 1) {
                    grid2[x][y] = 0;
                    stk.push(new int[] {x, y});
                }
            }
        }
        return ok;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public:
    int countSubIslands(vector<vector<int>>& grid1, vector<vector<int>>& grid2) {
        int m = grid1.size(), n = grid1[0].size();
        int ans = 0;
        int dirs[5] = {-1, 0, 1, 0, -1};
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (!grid2[i][j]) {
                    continue;
                }
                int ok = 1;
                vector<pair<int, int>> stk{{i, j}};
                grid2[i][j] = 0;
                while (!stk.empty()) {
                    auto [a, b] = stk.back();
                    stk.pop_back();
                    ok &= grid1[a][b];
                    for (int k = 0; k < 4; ++k) {
                        int x = a + dirs[k], y = b + dirs[k + 1];
                        if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y]) {
                            grid2[x][y] = 0;
                            stk.emplace_back(x, y);
                        }
                    }
                }
                ans += ok;
            }
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
func countSubIslands(grid1 [][]int, grid2 [][]int) (ans int) {
    m, n := len(grid1), len(grid1[0])
    dirs := [5]int{-1, 0, 1, 0, -1}
    for i := 0; i < m; i++ {
        for j := 0; j < n; j++ {
            if grid2[i][j] != 1 {
                continue
            }
            ok := 1
            grid2[i][j] = 0
            stk := [][2]int{{i, j}}
            for len(stk) > 0 {
                cur := stk[len(stk)-1]
                stk = stk[:len(stk)-1]
                ok &= grid1[cur[0]][cur[1]]
                for k := 0; k < 4; k++ {
                    x, y := cur[0]+dirs[k], cur[1]+dirs[k+1]
                    if x >= 0 && x < m && y >= 0 && y < n && grid2[x][y] == 1 {
                        grid2[x][y] = 0
                        stk = append(stk, [2]int{x, y})
                    }
                }
            }
            ans += ok
        }
    }
    return
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function countSubIslands(grid1: number[][], grid2: number[][]): number {
    const [m, n] = [grid1.length, grid1[0].length];
    let ans = 0;
    const dirs = [-1, 0, 1, 0, -1];
    const flood = (i: number, j: number): number => {
        let ok = 1;
        grid2[i][j] = 0;
        const stk: number[][] = [[i, j]];
        while (stk.length) {
            const [a, b] = stk.pop()!;
            ok &= grid1[a][b];
            for (let k = 0; k < 4; ++k) {
                const x = a + dirs[k];
                const y = b + dirs[k + 1];
                if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y]) {
                    grid2[x][y] = 0;
                    stk.push([x, y]);
                }
            }
        }
        return ok;
    };
    for (let i = 0; i < m; ++i) {
        for (let j = 0; j < n; j++) {
            if (grid2[i][j]) {
                ans += flood(i, j);
            }
        }
    }
    return ans;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
function countSubIslands(grid1, grid2) {
    const [m, n] = [grid1.length, grid1[0].length];
    let ans = 0;
    const dirs = [-1, 0, 1, 0, -1];
    const flood = (i, j) => {
        let ok = 1;
        grid2[i][j] = 0;
        const stk = [[i, j]];
        while (stk.length) {
            const [a, b] = stk.pop();
            ok &= grid1[a][b];
            for (let k = 0; k < 4; ++k) {
                const x = a + dirs[k];
                const y = b + dirs[k + 1];
                if (x >= 0 && x < m && y >= 0 && y < n && grid2[x][y]) {
                    grid2[x][y] = 0;
                    stk.push([x, y]);
                }
            }
        }
        return ok;
    };
    for (let i = 0; i < m; ++i) {
        for (let j = 0; j < n; j++) {
            if (grid2[i][j]) {
                ans += flood(i, j);
            }
        }
    }
    return ans;
}

Comments