题目:
给定一个由 0 和 1 组成的非空二维数组 grid ,用来表示海洋岛屿地图。
一个 岛屿 是由一些相邻的 1 (代表土地) 构成的组合,这里的「相邻」要求两个 1 必须在水平或者竖直方向上相邻。你可以假设 grid 的四个边缘都被 0(代表水)包围着。
找到给定的二维数组中最大的岛屿面积。如果没有岛屿,则返回面积为 0 。
示例 1:
输入: grid = [[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
解释: 对于上面这个给定矩阵应返回 6。注意答案不应该是 11 ,因为岛屿只能包含水平或垂直的四个方向的 1 。
示例 2:
输入: grid = [[0,0,0,0,0,0,0,0]]
输出: 0
提示:
m == grid.length
n == grid[i].length
1 <&#61; m, n <&#61; 50
grid[i][j] is either 0 or 1
注意&#xff1a;本题与主站 695 题相同&#xff1a; https://leetcode-cn.com/problems/max-area-of-island/
答案&#xff1a;
class Solution {public int maxAreaOfIsland(int[][] grid) {int max &#61; 0;int m &#61; grid.length, n &#61; grid[0].length;boolean[][] visited &#61; new boolean[m][n];for(int i &#61; 0; i < m; i&#43;&#43;){for(int j &#61; 0; j < n; j&#43;&#43;){if(!visited[i][j] && grid[i][j] &#61;&#61; 1) max &#61; Math.max(dfs(grid,visited, i, j, 0), max);}}return max;}public int dfs(int[][] grid, boolean[][] visited, int i, int j, int sum){System.out.println(i &#43; " " &#43; j);sum &#43;&#61; 1;visited[i][j] &#61; true;if(i > 0 && grid[i - 1][j] &#61;&#61; 1 && !visited[i - 1][j]) sum &#43;&#61; dfs(grid, visited, i - 1, j, 0);if(j < grid[0].length - 1 && grid[i][j &#43; 1] &#61;&#61; 1 && !visited[i][j &#43; 1]) sum &#43;&#61; dfs(grid, visited, i, j &#43; 1, 0);if(i < grid.length - 1 && grid[i &#43; 1][j] &#61;&#61; 1 && !visited[i &#43; 1][j]) sum &#43;&#61; dfs(grid, visited, i &#43; 1, j, 0);if(j > 0 && grid[i][j - 1] &#61;&#61; 1 && !visited[i][j - 1]) sum &#43;&#61; dfs(grid, visited, i, j - 1, 0);return sum;}
}