主页有其他数据结构内容(持续更新中)
难度:Medium
代码:
法一:dfs
class Solution {
private:
int count; // 计数器
int direction[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
void dfs(vector<vector<int>>& grid, vector<vector<bool>>& visited, int x, int y) {
for(int k = 0; k < 4; k++) {
int nextX = x + direction[k][0];
int nextY = y + direction[k][1];
if(nextX < 0 || nextX >= grid.size() || nextY < 0 || nextY >= grid[0].size()) {
continue;
}
if(!visited[nextX][nextY] && grid[nextX][nextY] == 1) {
visited[nextX][nextY] = true;
count++;
dfs(grid, visited, nextX, nextY);
}
}
}
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<bool>> visited(m, vector<bool>(n, false));
int res = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(!visited[i][j] && grid[i][j] == 1) {
visited[i][j] = true;
count = 1;
dfs(grid, visited, i, j);
res = max(res, count);
}
}
}
return res;
}
};
法二:bfs
class Solution {
private:
int count; // 计数器
int direction[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
void bfs(vector<vector<int>>& grid, vector<vector<bool>>& visited, int x, int y) {
queue<pair<int, int>> q;
q.push({x, y});
visited[x][y] = true;
while(!q.empty()) {
pair<int, int> cur = q.front();
q.pop();
for(int k = 0; k < 4; k++) {
int nextX = cur.first + direction[k][0];
int nextY = cur.second + direction[k][1];
if(nextX < 0 || nextX >= grid.size() || nextY < 0 || nextY >= grid[0].size()) {
continue;
}
if(!visited[nextX][nextY] && grid[nextX][nextY] == 1) {
q.push({nextX, nextY});
visited[nextX][nextY] = true;
count++;
}
}
}
}
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<bool>> visited(m, vector<bool>(n, false));
int res = 0;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(!visited[i][j] && grid[i][j] == 1) {
count = 1;
bfs(grid, visited, i, j);
res = max(res, count);
}
}
}
return res;
}
};