# LeetCode-695. 岛屿的最大面积

## 题目描述

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


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


## 解题思路

### DFS

class SolutionDFS {
public:
int maxAreaOfIsland(vector<vector<int>>& grid)
{
if(grid.empty())
return 0;

int res = 0;

// 定义标记数组
vector<vector<bool>> vecMark(grid.size(),vector<bool>(grid[0].size(),false));

// 定义搜索边界
int mostDeep = grid.size();
int mostLeft = grid[0].size();

//开始搜索
for(int i = 0;i < mostDeep;i++)
{
for(int j = 0;j < mostLeft;j++)
{
if(vecMark[i][j] == true)
continue;
int temp = dfs(grid, i, j, vecMark);
res = max(res, temp);
}
}

return res;
}
private:
int dfs(vector<vector<int>>& grid, int x, int y,vector<vector<bool>>& mark)
{
if(x >=  grid.size() || y >= grid[0].size() || x < 0 || y < 0)
return 0;

if(mark[x][y] == true)
return 0;
if(grid[x][y] == 0)
return 0;

// 对于点[x,y]搜索上下左右4个点是否是岛屿
// 即[x-1,y],[x+1,y],[x,y-1],[x,y+1]
// 对于已经搜索过的点要进行标记

mark[x][y] = true;

return 1 + dfs(grid, x+1, y, mark) + dfs(grid, x-1, y, mark) + dfs(grid, x, y+1, mark) + dfs(grid, x, y-1, mark);
}
};


### BFS

class SolutionBFS{
public:
int maxAreaOfIsland(vector<vector<int>>& grid)
{
if(grid.empty())
return 0;

int res = 0;

// 定义标记数组
vector<vector<bool>> vecMark(grid.size(),vector<bool>(grid[0].size(),false));

// 定义搜索边界
int mostDeep = grid.size();
int mostLeft = grid[0].size();

//开始搜索
for(int i = 0;i < mostDeep;i++)
{
for(int j = 0;j < mostLeft;j++)
{
if(vecMark[i][j] == true)
continue;

if(grid[i][j] == 0)
continue;

int itempArea = 0;
//定义临时栈
stack<pair<int,int>> stackTemp;
stackTemp.push(make_pair(i,j));
vecMark[i][j] = true;

while(!stackTemp.empty())
{
itempArea++;

pair<int,int> curPoint = stackTemp.top();
stackTemp.pop();

int x = curPoint.first;
int y = curPoint.second;

if(x-1 >= 0 && grid[x-1][y] == 1 && vecMark[x-1][y] == false)
{
stackTemp.push(make_pair(x-1, y));
vecMark[x-1][y] = true;
}

if(x+1 < mostDeep && grid[x+1][y] == 1 && vecMark[x+1][y] == false)
{
stackTemp.push(make_pair(x+1, y));
vecMark[x+1][y] = true;
}

if(y-1 >= 0 && grid[x][y-1] == 1 && vecMark[x][y-1] == false)
{
stackTemp.push(make_pair(x, y-1));
vecMark[x][y-1] = true;
}

if(y+1 < mostLeft && grid[x][y+1] == 1 && vecMark[x][y+1] == false)
{
stackTemp.push(make_pair(x, y+1));
vecMark[x][y+1] = true;
}
}
res = max(res, itempArea);
}
}

return res;
}
};

posted @ 2018-07-21 22:31  Blue影  阅读(1534)  评论(0编辑  收藏  举报