# LeetCode 面试题 16.19. 水域大小 （DFS）

[
[0,2,1,0],
[0,1,0,1],
[1,1,0,1],
[0,1,0,1]
]

0 < len(land) <= 1000
0 < len(land[i]) <= 1000

 1 /**
2  * Note: The returned array must be malloced, assume caller calls free().
3  */
4 int t;
5 int cmp(void* a,void* b)
6 {
7     return *(int*)a-*(int*)b;
8 }
9 void dfs(int** land, int landSize, int* landColSize,int x,int y)
10 {
11     int i,j;
12     t++;
13     for(int dx=-1;dx<=1;dx++){
14         for(int dy=-1;dy<=1;dy++){
15             int nx=x+dx,ny=y+dy;
16             if(nx>=0&&nx<landSize&&ny>=0&&ny<landColSize[0]&&land[nx][ny]==0){
17                 land[nx][ny]=1;
18                 dfs(land,landSize,landColSize,nx,ny);
19             }
20         }
21     }
22 }
23 int* pondSizes(int** land, int landSize, int* landColSize, int* returnSize){
24     if(land==NULL||landSize==0){
25         *returnSize=0;
26         return NULL;
27     }
28     int* area=(int*)malloc(sizeof(int)*(landSize*landColSize[0]));
29     int cnt=0,i,j;
30     for(i=0;i<landSize;i++){
31         for(j=0;j<landColSize[0];j++){
32             if(land[i][j]==0){
33                 t=0;
34                 dfs(land,landSize,landColSize,i,j);
35                 area[cnt++]=t-1;
36             }
37         }
38     }
39     *returnSize=cnt;
40     qsort(area,cnt,sizeof(int),cmp);
41     return area;
42 }

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