LeetCode 695 Max Area of Island DFS
You are given an m x n
binary matrix grid
. An island is a group of 1's (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.
The area of an island is the number of cells with a value 1 in the island.
Return the maximum area of an island in grid. If there is no island, return 0.
Solution
求每一块land中的最大值。我们对于每一个land进行 \(DFS\):
点击查看代码
class Solution {
private:
int ans = 0;
int dir[4][2]={0,1, 1,0, -1,0, 0,-1};
int vis[52][52];
bool check(int x, int y, int r, int c){
if(x<0||y<0||x>=r||y>=c)return false;
return true;
}
void dfs(int x,int y, vector<vector<int>>& grid, int& cur_sum){
if(vis[x][y]||grid[x][y]==0)return;
if(grid[x][y]==1){
vis[x][y] = 1;
cur_sum+=1;
ans=max(ans,cur_sum);
for(int i=0;i<4;i++){
int nx = x+dir[i][0], ny = y+dir[i][1];
if(check(nx,ny,grid.size(),grid[0].size())){
dfs(nx,ny, grid,cur_sum);
}
}
}
}
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int r = grid.size(), c = grid[0].size();
int cur;
for(int i=0;i<r;i++){
for(int j=0;j<c;j++){
if(vis[i][j]==0 && grid[i][j]==1)
cur = 0, dfs(i,j,grid,cur);
}
}
return ans;
}
};