March punch card activity on the 15th day LeetCode 695 title: Islands maximum area (medium)
Title: Given a two-dimensional array of non-null grid number 0 and 1, is an island formed of a combination of four directions (horizontal or vertical) 1 (representing the land). You can assume that the four edges of the two-dimensional matrix are surrounded by water. Find a given two-dimensional array in the largest island in the area. (If there are no islands, the area is returned to 0.)
Problem solution approach: that is the way it should weekend, every weekend the title is not good to do, to make explanations Well, I just do not want to question ~~
classSolution{publicintmaxAreaOfIsland(int[][] grid){int res =0;for(int i =0; i < grid.length; i++){for(int j =0; j < grid[i].length; j++){if(grid[i][j]==1){
res = Math.max(res,dfs(i, j, grid));}}}return res;}// 每次调用的时候默认num为1,进入后判断如果不是岛屿,则直接返回0,就可以避免预防错误的情况。// 每次找到岛屿,则直接把找到的岛屿改成0,这是传说中的沉岛思想,就是遇到岛屿就把他和周围的全部沉默。// ps:如果能用沉岛思想,那么自然可以用朋友圈思想。有兴趣的朋友可以去尝试。privateintdfs(int i,int j,int[][] grid){if(i <0|| j <0|| i >= grid.length || j >= grid[i].length || grid[i][j]==0){return0;}
grid[i][j]=0;int num =1;
num +=dfs(i +1, j, grid);
num +=dfs(i -1, j, grid);
num +=dfs(i, j +1, grid);
num +=dfs(i, j -1, grid);return num;}}
作者:mark-42
链接:https://leetcode-cn.com/problems/max-area-of-island/solution/biao-zhun-javadong-tai-gui-hua-jie-fa-100-by-mark-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。