给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。)
示例 1:
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
对于上面这个给定矩阵应返回 6。注意答案不应该是11,因为岛屿只能包含水平或垂直的四个方向的‘1’。示例 2:
[[0,0,0,0,0,0,0,0]]
对于上面这个给定的矩阵, 返回 0。注意: 给定的矩阵grid 的长度和宽度都不超过 50。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/max-area-of-island
Javascript 代码实现:
/** * @param {number[][]} grid * @return {number} */ var max = 0; var visited = []; var fillVisited = function(leni, lenj){ for(let i = 0; i < leni; i++){ visited[i] = []; for(let j = 0; j < lenj; j++){ visited[i].push(0);// 全0数组 } } return visited; }; var maxAreaOfIsland = function(grid) { let maxx = 0; visited = fillVisited(grid.length, grid[0].length);// 行数和列数 for(let i = 0; i < grid.length; i++){ for(let j = 0; j < grid[0].length; j++){ if(grid[i][j] == 1){ max = 0; let ans = check(grid, i, j); if(maxx < ans){ maxx = ans; } } } } return maxx; }; var check = function(grid,i,j){ if(!(i>=0 && i<grid.length && j>=0 && j<grid[0].length)||grid[i][j]!=1||visited[i][j]) return 0; visited[i][j] = 1; return check(grid,i,j-1)+check(grid,i,j+1)+ check(grid,i-1,j)+check(grid,i+1,j)+1; };