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]
andgrid2[i][j]
are either0
or1
.
Related Topics:
Depth-first Search, Union Find
Similar Questions:
Intuition: If an island in B
overlaps with a water cell in A
, then this island shouldn't be considered.
Algorithm
- For each water cell
A[i][j]
, sink the island inB
containingB[i][j]
into water. - Count the number of islands in
B
.
// OJ: https://leetcode.com/problems/count-sub-islands/
// Author: github.com/lzl124631x
// Time: O(MN)
// Space: O(1)
class Solution {
int dirs[4][2] = {{0,1},{0,-1},{-1,0},{1,0}}, M, N;
void dfs(vector<vector<int>> &B, int x, int y, int color) {
if (B[x][y] == color) return;
B[x][y] = color;
for (auto &[dx, dy] : dirs) {
int a = x + dx, b = y + dy;
if (a < 0 || a >= M || b < 0 || b >= N) continue;
dfs(B, a, b, color);
}
}
public:
int countSubIslands(vector<vector<int>>& A, vector<vector<int>>& B) {
M = A.size(), N = A[0].size();
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (A[i][j] == 0) dfs(B, i, j, 0); // sink this island at B[i][j]
}
}
int cnt = 0;
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if (B[i][j] == 1) {
dfs(B, i, j, 0);
++cnt; // count islands in `B`
}
}
}
return cnt;
}
};