方法一:BFS
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int row = grid.size(), col = grid[0].size();
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
int ans = 0;
for(int i = 0; i < row; ++i)
for(int j = 0; j < col; ++j)
if(grid[i][j]) // BFS开始
{
queue<pair<int, int>> q;
q.push(make_pair(i, j));
int temp_ans = 1;
grid[i][j] = 0; // 已经访问过
while(!q.empty())
{
auto node = q.front();
q.pop();
for(int k = 0; k < 4; ++k)
{
int newI = node.first + dx[k], newJ = node.second + dy[k];
if(newI >= 0 && newI < row && newJ >= 0 && newJ < col && grid[newI][newJ])
// 该位置有效且可以走
{
q.push(make_pair(newI, newJ));
grid[newI][newJ] = 0;
++temp_ans;
}
}
}
ans = max(ans, temp_ans);
}
return ans;
}
};
方法二:DFS
class Solution {
int row, col;
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int ans = 0;
row = grid.size(), col = grid[0].size();
for(int i = 0; i < row; ++i)
for(int j = 0; j < col; ++j)
if(grid[i][j]) ans = max(ans, DFS(i, j, grid));
return ans;
}
int DFS(int i, int j, vector<vector<int>>& grid)
{
int ans = 1; // 有效才会进入DFS
grid[i][j] = 0; // 置为无效,确保DFS时不会回头
for(int k = 0; k < 4; ++k)
{
int newI = i + dx[k], newJ = j + dy[k];
if(newI >= 0 && newI < row && newJ >= 0 && newJ < col && grid[newI][newJ])
ans += DFS(newI, newJ, grid);
}
return ans;
}
};