1、BFS
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int maxArea = 0, rows = grid.size(), columns = grid[0].size();
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns; ++j) {
if (grid[i][j] == 1) {
maxArea = max(maxArea,BFS(grid, i, j));
}
}
}
return maxArea;
}
private:
int BFS(vector<vector<int>>& grid, int row, int column){
int rows = grid.size(), columns = grid[0].size(), ans = 1;
queue<pair<int, int>> q;
q.push({row,column});
grid[row][column] = 2;
vector<int> dir({0,1,0,-1,0});
while (!q.empty()) {
int r = q.front().first;
int c = q.front().second;
q.pop();
for (int i = 0; i < 4; ++i) {
int rr = r + dir[i];
int cc = c + dir[i+1];
if (0 <= rr && rr < rows && 0 <= cc && cc < columns && grid[rr][cc] == 1) {
++ans;
q.push({rr,cc});
grid[rr][cc] = 2;
}
}
}
return ans;
}
};
网友评论