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
.
Solution: Coloring
Give each island in grid1 a different color. Whiling using the same method to find island and coloring it in grid2, we also check whether the same cell in grid1 always has the same color.
Time complexity: O(mn)
Space complexity: O(1) modify in place or O(mn)
C++
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 |
// Author: Huahua class Solution { public: int countSubIslands(vector<vector<int>>& grid1, vector<vector<int>>& grid2) { const int m = grid1.size(); const int n = grid1[0].size(); int valid = 1; function<void(int, int, int, int)> color = [&](int i, int j, int c, int p) { if (i < 0 || i >= m || j < 0 || j >= n) return; auto& gc = p ? grid2 : grid1; auto& go = p ? grid1 : grid2; if (gc[i][j] != 1) return; gc[i][j] = c; if (p && go[i][j] != c) valid = 0; color(i + 1, j, c, p); color(i - 1, j, c, p); color(i, j + 1, c, p); color(i, j - 1, c, p); }; for (int i = 0, c = 2; i < m; ++i) for (int j = 0; j < n; ++j) if (grid1[i][j] == 1) color(i, j, c++, 0); int ans = 0; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (grid2[i][j] == 1 && grid1[i][j]) { valid = 1; color(i, j, grid1[i][j], 1); ans += valid; } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment