# LeetCode 695. 岛屿的最大面积 （DFS）

[[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]]

[[0,0,0,0,0,0,0,0]]

 1 int dx[4]={1,-1,0,0};
2 int dy[4]={0,0,1,-1};
3 int res,maxc;
4 void dfs(int** grid, int gridSize, int* gridColSize,int x,int y)
5 {
6     int i,j;
7     res++;
8     grid[x][y]=0;
9     for(i=0;i<4;i++){
10         int nx=x+dx[i],ny=y+dy[i];
11         if(nx>=0&&nx<gridSize&&ny>=0&&ny<gridColSize[0]&&grid[nx][ny]==1){
12             dfs(grid,gridSize,gridColSize,nx,ny);
13         }
14     }
15     return ;
16 }
17 int maxAreaOfIsland(int** grid, int gridSize, int* gridColSize){
18     int i,j;
19     maxc=0;
20     res=0;
21     for(i=0;i<gridSize;i++){
22         for(j=0;j<gridColSize[0];j++){
23             if(grid[i][j]==1){
24                 res=0;
25                 dfs(grid,gridSize,gridColSize,i,j);
26                 if(res>maxc) maxc=res;
27             }
28         }
29     }
30     return maxc;
31 }

C++复习一遍：

 1 class Solution {
2 public:
3     int n,m,i,j;
4     void dfs(vector<vector<int>>& grid,int *num,int x,int y)
5     {
6         if(x<0||x>=n||y<0||y>=m||grid[x][y]==0) return;
7         grid[x][y]=0;
8         *num=(*num)+1;
9         dfs(grid,num,x+1,y);
10         dfs(grid,num,x-1,y);
11         dfs(grid,num,x,y+1);
12         dfs(grid,num,x,y-1);
13     }
14     int maxAreaOfIsland(vector<vector<int>>& grid) {
15         if(grid.size()==0) return 0;
16         n=grid.size(),m=grid[0].size();
17         int maxn=0,num=0;
18         for(i=0;i<n;i++){
19             for(j=0;j<m;j++){
20                 if(grid[i][j]==1){
21                     num=0;
22                     dfs(grid,&num,i,j);
23                     if(num>maxn) maxn=num;
24                 }
25             }
26         }
27         return maxn;
28     }
29 };

posted @ 2020-03-16 08:42  午夜的行人  阅读(23)  评论(0编辑  收藏
Live2D