宽度优先搜索。
class Solution {
public:
typedef pair<int, int> PII;
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; //BFS题专用偏移量
int area;
int maxAreaOfIsland(vector<vector<int>>& grid) {
for (int i = 0; i < grid.size(); i ++ ) //遍历每一块土地,值为1就用bfs展开岛屿
for (int j = 0; j < grid[0].size(); j ++ )
{
if (grid[i][j] == 1)
bfs(grid, i, j);
}
return area;
}
void bfs(vector<vector<int>>& grid, int i, int j)
{
int tmp_area = 1; //存在岛屿,即岛屿最小面积为1
queue<PII> q; //q存的是当前岛屿中值为1的坐标对
q.push({i, j});
while (q.size())
{
auto t = q.front();
q.pop();
grid[t.first][t.second] = 0;
for (int k = 0; k < 4; k ++ )
{
int x = t.first + dx[k], y = t.second + dy[k];
if (x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size() && grid[x][y] == 1)
{
q.push({x, y}); //下一个可扩展点入队
tmp_area ++ ; //当前岛屿面积加1
grid[x][y] = 0; //计算过的地方就不重复计算了,直接标记为0
}
}
}
area = max(area, tmp_area); //更新岛屿最大面积
}
};