Skip to content

695.Max Area of Island cpp version(16 ms) #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 16, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions solution/695.Max Area of Island/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
## 岛屿的最大面积
### 题目描述

给定一个包含了一些 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。
```

### 解法
搜索

```
```
51 changes: 51 additions & 0 deletions solution/695.Max Area of Island/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
class Solution {
public:
bool v[55][55] = {0, } ; // ���ʱ��
int maxAreaOfIsland(vector<vector<int>>& grid)
{
int maxAera = 0 ;
for (int i = 0; i < grid.size(); ++i)
{
if (0 == grid.size())
{
return 0 ;
}

for (int j = 0; j < grid[0].size(); ++j)
{
if (1 == grid[i][j] && !v[i][j])
{
int cnt = calcAera(grid, i, j) ;
if (cnt > maxAera)
maxAera = cnt ;
}
}
}
return maxAera ;
}

int calcAera(vector<vector<int>>& grid, int i, int j)
{
if (i < 0 || i >= grid.size())
return 0 ;
if (j < 0 || j >= grid[0].size())
return 0 ;

if (v[i][j])
return 0 ;

v[i][j] = true ;


if (grid[i][j])
{
return 1
+ calcAera(grid, i-1, j)
+ calcAera(grid, i+1, j)
+ calcAera(grid, i, j-1)
+ calcAera(grid, i, j+1) ;
}
else
return 0 ;
}
} ;