695.岛屿的最大面积 (Medium)*
题目描述*
给定一个包含了一些 0 和 1 的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为 0。)
注意*
给定的矩阵 grid 的长度和宽度都不超过 50。
代码*
跟岛屿数量那个差不多,稍微改一下就行。
class Solution {
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] != 1) {
return 0;
}
grid[i][j] = 2;
return dfs(grid, i + 1, j) + dfs(grid, i - 1, j) +
dfs(grid, i, j + 1) + dfs(grid, i, j - 1) + 1;
}
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int res = 0;
for(int i = 0; i < grid.size(); i++) {
for(int j = 0; j < grid[0].size(); j++) {
if(grid[i][j] == 1) {
int cur = dfs(grid, i, j);
if(cur > res) {
res = cur;
}
}
}
}
return res;
}
};
class Solution {
int bfs(vector<vector<int>>& grid, int i, int j, int rows, int cols) {
// 二维转一维
queue<int> q;
q.push(i * cols + j);
int cnt = 0;
while(!q.empty()) {
int cur = q.front();
q.pop();
int row = cur / cols;
int col = cur % cols;
if(grid[row][col] == 2) {
continue;
}
// 判断 当前为 1 才加 1
cnt++;
grid[row][col] = 2;
if(row != rows - 1 && grid[row + 1][col] == 1) {
q.push((row + 1) * cols + col);
}
if(row != 0 && grid[row - 1][col] == 1) {
q.push((row - 1) * cols + col);
}
if(col != cols - 1 && grid[row][col + 1] == 1) {
q.push(row * cols + col + 1);
}
if(col != 0 && grid[row][col - 1] == 1) {
q.push(row * cols + col - 1);
}
}
return cnt;
}
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int rows = grid.size();
int cols = grid[0].size();
int res = 0;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
if(grid[i][j] == 1) {
int cur = bfs(grid, i, j, rows, cols);
if(cur > res) {
res = cur;
}
}
}
}
return res;
}
};
最后更新: July 23, 2022