标签:Count grid1 help grid2 int island Islands false 1905
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.
class Solution { public int countSubIslands(int[][] grid1, int[][] grid2) { int res = 0; for(int i = 0; i < grid1.length; i++) { for(int j = 0; j < grid1[0].length; j++) { if(grid2[i][j] == 1) { if(help(grid1, grid2, i, j)) res++; } } } return res; } public boolean help(int[][] grid1, int[][] grid2, int i, int j) { if(i < 0 || i >= grid1.length || j < 0 || j >= grid1[0].length ) return true; if(grid2[i][j] == 0) return true; if(grid1[i][j] != grid2[i][j]) return false; grid2[i][j] = 0; boolean flag = true; if(!help(grid1, grid2, i + 1, j)) flag = false; if(!help(grid1, grid2, i - 1, j)) flag = false; if(!help(grid1, grid2, i, j + 1)) flag = false; if(!help(grid1, grid2, i, j - 1)) flag = false; return flag; } }
吃一堑,长一智,老老实实四个方向一个一个来。注意边界条件返回true 还是false
标签:Count,grid1,help,grid2,int,island,Islands,false,1905 来源: https://www.cnblogs.com/wentiliangkaihua/p/15018383.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。