模板题。。
思路一:dfs
class Solution {
public:
int ans = 0;
int flag[51][51] = {0};
int xy[4][2] = {0, 1, 0, -1, 1, 0, -1, 0};
int dfs(vector<vector<int>>& grid, int x, int y) {
int n = grid.size(), m = grid[0].size();
flag[x][y] = 1;
int cnt = 1;
for (int i = 0; i < 4; ++i) {
int xx = x + xy[i][0], yy = y + xy[i][1];
if (xx < 0 || xx > n - 1 || yy < 0 || yy > m - 1) continue;
if (grid[xx][yy] == 1 && !flag[xx][yy]) cnt += dfs(grid, xx, yy);
}
return cnt;
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (grid[i][j] == 1 && !flag[i][j]) ans = max(ans, dfs(grid, i, j));
}
}
return ans;
}
};
思路二:bfs
int bfs(vector<vector<int>>& grid, int x, int y) {
int n = grid.size(), m = grid[0].size();
int cnt = 0;
queue<pair<int, int>> q;
q.push({x, y});
flag[x][y] = 1;
while (!q.empty()) {
auto frt = q.front();
int first = frt.first, second = frt.second;
q.pop();
cnt++;
for (int i = 0; i < 4; ++i) {
int xx = first + xy[i][0];
int yy = second + xy[i][1];
if (xx < 0 || yy < 0 || xx >= n || yy >= m) continue;
if (grid[xx][yy] && !flag[xx][yy]) {
q.push({xx, yy});
flag[xx][yy] = 1;
}
}
}
return cnt;
}