遍历每个位置,使用深度优先搜索获取每个岛屿的面积
访问过的地方置为0,防止重复访问
var maxAreaOfIsland = function(grid) {let row = grid.length;let col = grid[0].length;let res = 0;for(let i=0;i<row;i++){for(let j=0;j<col;j++){res = Math.max(dfs(grid,i,j),res);}}return res;};function dfs(grid,r,c){//超出边界或位置在水上if(r<0 || r>=grid.length || c<0 || c>=grid[0].length || grid[r][c]===0){return 0;}grid[r][c] = 0;//访问过的置为0,避免重复计算let res = 1;//遍历四个方向for(let item of [[0,1],[0,-1],[1,0],[-1,0]]){res += dfs(grid,r+item[0],c+item[1]);}return res;}
