695. Max Area of Island
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.
题目:找最大岛屿大小。
解法:BFS或DFS
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid)
{
int row = grid.size();
int col = grid[0].size();
int ret = 0;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (grid[i][j] == 1)
{
ret = max(ret, DFS(i, j, grid, row, col) );
}
}
}
return ret;
}
private:
int a[4] = {0, 1, 0, -1};
int b[4] = {1, 0, -1, 0};
int BFS(int i, int j, vector<vector<int>>& grid, int row, int col)
{
int ret = 0;
grid[i][j] = 2;
queue<pair<int, int>> que;
que.push(make_pair(i, j));
while (!que.empty())
{
ret ++;
int x = que.front().first, y = que.front().second;
que.pop();
for (int k = 0; k < 4; k++)
{
int _x = x + a[k], _y = y + b[k];
if ( isvaild(_x, _y, row, col) && grid[_x][_y] == 1)
{
que.push(make_pair(_x, _y));
grid[_x][_y] = 2; //有了这一步就可以不需要hash表来记录那些点遍历过。因为变成2就不可能再被遍历。
}
}
}
return ret;
}
int DFS(int i, int j, vector<vector<int>>& grid, int row, int col)
{
int ret = 0;
grid[i][j] = 2;
stack<pair<int, int> >stk;
stk.push(make_pair(i, j));
while (!stk.empty())
{
bool hasfindone = false; //DFS不用函数嵌套的写法就必须要一个记录当前点周围必须没有新的点加入,才能把当前点pop,不然会找不到当前点的其他邻接点。
int x = stk.top().first, y = stk.top().second;
for (int k = 0; k < 4; k++)
{
int _x = x + a[k], _y = y + b[k];
if (isvaild(_x, _y, row, col) && grid[_x][_y] == 1)
{
hasfindone = true;
grid[_x][_y] = 2;
stk.push(make_pair(_x, _y));
break;
}
}
if (!hasfindone) //这个点周围都没有了。
{
stk.pop();
ret ++;
}
}
return ret;
}
bool isvaild(int x, int y, int row, int col)
{
return x >= 0 && x < row && y >= 0 && y < col;
}
};