zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    BZOJ3501 : PA2008 Cliquers Strike Back
    BZOJ3500 : PA2008 Cliquers
    BZOJ2280 : [Poi2011]Plot
    BZOJ2924 : [Poi1998]Flat broken lines
    BZOJ2911 : [Poi1997]The Number of Symmetrical Choices
    BZOJ2612 : [Poi2003]Sums
    BZOJ4025 : 二分图
    BZOJ2213 : [Poi2011]Difference
    BZOJ2215 : [Poi2011]Conspiracy
    BZOJ2278 : [Poi2011]Garbage
  • 原文地址:https://www.cnblogs.com/shixinzei/p/12501877.html
Copyright © 2011-2022 走看看