跳至主要内容

695. Max Area of Island

  • DFS
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid)
{
int maxArea = 0;
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[0].size(); j++)
{
maxArea = max(maxArea, dfs(grid, i, j));
}
}
return maxArea;
}

int dfs(vector<vector<int>>& grid, int i, int j)
{
if (i < 0 || j < 0 || i >= grid.size() || j >= grid[0].size() || grid[i][j] == 0) return 0;

int area = 1;
grid[i][j] = 0;
vector<vector<int>> directions = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}};
for (const auto& dir : directions)
{
area += dfs(grid, i + dir[0], j + dir[1]);
}
return area;
}
};
  • T: O(MN)O(M \cdot N)

  • S: O(MN)O(M \cdot N)

  • BFS

class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid)
{
int maxArea = 0;
vector<vector<int>> directions = {{0, -1}, {0, 1}, {1, 0}, {-1, 0}};
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[0].size(); j++)
{
if (grid[i][j] == 0) continue;
int area = 1;
queue<vector<int>> q;
q.push({i, j});
grid[i][j] = 0;
while (!q.empty())
{
auto node = q.front(); q.pop();
for (const auto& dir : directions)
{
int new_i = node[0] + dir[0];
int new_j = node[1] + dir[1];
if (new_i < 0 || new_j < 0 || new_i >= grid.size() || new_j >= grid[0].size() || grid[new_i][new_j] == 0)
continue;

grid[new_i][new_j] = 0;
area++;
q.push({new_i, new_j});
}
}
maxArea = max(maxArea, area);
}
}
return maxArea;
}
};
  • T: O(MN)O(M \cdot N)
  • S: O(MN)O(M \cdot N)