LeetCode 面試題 16.19. 水域大小 (DFS)


題目鏈接:https://leetcode-cn.com/problems/pond-sizes-lcci/

你有一個用於表示一片土地的整數矩陣land,該矩陣中每個點的值代表對應地點的海拔高度。若值為0則表示水域。由垂直、水平或對角連接的水域為池塘。池塘的大小是指相連接的水域的個數。編寫一個方法來計算矩陣中所有池塘的大小,返回值需要從小到大排序。

示例:

輸入:
[
[0,2,1,0],
[0,1,0,1],
[1,1,0,1],
[0,1,0,1]
]
輸出: [1,2,4]
提示:

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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM