[Leetcode]695. Max Area of Island

时间:2024-04-29 08:07:22

Given a non-empty 2D array grid of 0's and 1's, an island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

Example 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]]

Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.

Example 2:

[[0,0,0,0,0,0,0,0]]

Given the above grid, return 0.

Note: The length of each dimension in the given grid does not exceed 50.

思路:深度优先搜索。从第一行第一个开始遍历整个数组,如果某个位置的值是 1 ,那么就开始深度优先搜索。

在深度优先搜索中,我们先要看看与该位置连通有几种可能的情况,很明显是4种,即上下左右。所以我们得用

个循环来遍历这四种可能的情况。如果上或下或左或右的值是1,我们就用递归函数递归上或下或左或右的位置,

求解他们连通的情况。

 class Solution {
private int sum = 0,maxSum = 0;
public int maxAreaOfIsland(int[][] grid) {
for (int i=0;i<grid.length;i++){
for (int j=0;j<grid[i].length;j++){
if (grid[i][j]==1){
sum = 0;
dfs(grid,i,j);
}
}
}
return maxSum;
}
private void dfs(int[][] grid,int i,int j){
sum +=grid[i][j];
grid[i][j]= 0;
if (i-1>=0&&grid[i-1][j]==1)
dfs(grid,i-1,j);
if (i+1<grid.length&&grid[i+1][j]==1)
dfs(grid,i+1,j);
if (j-1>=0&&grid[i][j-1]==1)
dfs(grid,i,j-1);
if (j+1<grid[i].length&&grid[i][j+1]==1)
dfs(grid,i,j+1);
if (sum>maxSum){
maxSum = sum;
} }
}