Problem
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.)
Note: The length of each dimension in the given grid does not exceed 50.
Example1
[[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.
EXample2
[[0,0,0,0,0,0,0,0]]
Given the above grid, return 0.
Solution
DFS
辅助二维数组visited,标识每一个位置是否访问过。
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int rows = grid.size();
if(rows == 0)
return 0;
int maxIslandArea = 0;
int cols = grid[0].size();
std::vector<std::vector<int>> visited(rows, std::vector<int>(cols, 0));
vector<pair<int,int>> direction = {{-1,0},{1,0},{0,-1},{0,1}};
queue<pair<int,int>> q;
for(int i = 0;i<rows;++i)
{
for(int j = 0;j<cols;++j)
{
if(grid[i][j] == 0 || visited[i][j] == 1)
continue;
else
{
q.push(pair<int,int>(i,j));
visited[i][j] = 1;
int curIslandArea = 0;
while(!q.empty())
{
pair<int,int> cur = q.front();
q.pop();
++curIslandArea;
for(int k = 0;k<direction.size();++k)
{
int row = cur.first + direction[k].first;
int col = cur.second + direction[k].second;
if(row>=0 && row < rows && col >=0 && col<cols && grid[row][col] == 1 && visited[row][col] == 0)
{
q.push(pair<int,int>(row,col));
visited[row][col] = 1;
}
}
}
if(curIslandArea > maxIslandArea)
maxIslandArea = curIslandArea;
}
}
}
return maxIslandArea;
}
};
类似题目
994. Rotting Oranges