695. 岛屿的最大面积
DFS
递归解法
class Solution { public: int maxAreaOfIsland(vector<vector<int>> &grid) { int res = 0; int row = grid.size(); int column = grid[0].size(); for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { if (grid[i][j]) { res = max(res, DFS(grid, i, j)); } } } return res; } int DFS(vector<vector<int>> &grid, int curX, int curY) { int row = grid.size(); int column = grid[0].size(); // 边界直接返回 if (curX == row || curX < 0 || curY == column || curY < 0 || grid[curX][curY] == 0) { return 0; } grid[curX][curY] = 0; return 1 + DFS(grid, curX + 1, curY) + DFS(grid, curX, curY + 1) + DFS(grid, curX - 1, curY) + DFS(grid, curX, curY - 1); } };
栈解法
class Solution { public: vector<int> direction{-1, 0, 1, 0, -1}; int maxAreaOfIsland(vector<vector<int>> &grid) { int m = grid.size(); int n = grid[0].size(); int local_area, area = 0, x, y; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j]) { local_area = 1; grid[i][j] = 0; stack<pair<int, int>> island; island.push({i, j}); while (!island.empty()) { auto [r, c] = island.top(); island.pop(); for (int k = 0; k < 4; k++) { x = r + direction[k]; y = c + direction[k + 1]; if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1) { grid[x][y] = 0; local_area++; island.push({x, y}); } } } area = max(area, local_area); } } } return area; } };