题目
给定一个包含了一些 0 和 1的非空二维数组 grid , 一个 岛屿 是由四个方向 (水平或垂直) 的 1 (代表土地) 构成的组合。你可以假设二维矩阵的四个边缘都被水包围着。
找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为0。)
示例1
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
思路
- 遍历每一个坐标作为开始,每一个坐标都去递归的遍历上下左右,遍历过的标记为遍历过,下次就不再遍历。记录每一个坐标作为开始时的岛屿面积,取最大的。
代码
class Solution {
private:
vector<vector<bool>> used;
vector<vector<int>> pattern;
int rows;
int cols;
int maxArea;
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
if ( grid.size() == 0 ) return 0;
rows = grid.size();
cols = grid[0].size();
maxArea = 0;
used = vector<vector<bool>>( rows, vector<bool>( cols, false ) );
pattern = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
for ( int i = 0; i < rows; ++i ) {
for ( int j = 0; j < cols; ++j ) {
if ( !used[i][j] && grid[i][j] == 1 ) {
int temp = 1;
helper( grid, i, j, temp );
maxArea = max( maxArea, temp );
}
}
}
return maxArea;
}
void helper( vector<vector<int>>& grid, int row, int col, int& temp ) {
used[row][col] = true;
for ( auto& vec : pattern ) {
int newRow = row + vec[0];
int newCol = col + vec[1];
if ( isValid(grid, newRow, newCol) && !used[newRow][newCol] ) {
++temp;
helper( grid, newRow, newCol, temp );
}
}
return;
}
bool isValid(vector<vector<int>>& grid, int& row, int& col ) {
return row >=0 && row < rows
&& col >= 0 && col < cols
&& grid[row][col] == 1;
}
};