解题思路:题目意思是在数组里面寻找相连的1的个数。首先对数组进行循环,遇到“1”时开始计算面积,通过对方向”上“,”下“,”左“,”右“进行寻找,遇到1,temp就+1。并且为了使已经遍历过的不再重复计算,在遍历后将其赋值为“0”表示已经遍历过。最后得出每次计算面积中的最大值即可。
class Solution {
public:
void dfs(int x, int y, int& temp, vector<vector<int>>& grid){
if(x < 0 || x >= grid.size() || y < 0 || y >= grid[0].size() || grid[x][y] != 1) return ;
grid[x][y] = 0;
temp++;
dfs(x+1, y, temp, grid);
dfs(x, y-1, temp, grid);
dfs(x-1, y, temp, grid);
dfs(x, y+1, temp, grid);
return ;
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
int row = grid.size();
if(row == 0) return 0;
int ans=0, col = grid[0].size();
for(int i = 0;i < row;i ++){
for(int j = 0;j < col;j ++){
if(grid[i][j]==1){
int temp = 0;
dfs(i, j, temp, grid);
ans = max(temp, ans);
}
}
}
return ans;
}
};