leetcode#搜索#水域大小模型总结#19.水域大小

面试题 16.19. 水域大小

Difficulty: 中等

你有一个用于表示一片土地的整数矩阵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
Solution

Language: 全部题目


class Solution {
    public int[] pondSizes(int[][] land) {
        List<Integer> list = new ArrayList<>();
        int m = land.length, n = land[0].length;
        for(int i=0;i<m;++i) {
            for(int j=0;j<n;++j) {
                 int area = dfs(i,j,m,n,land);
                 if (area> 0) list.add(area);
            }
        }

        list.sort((i,j)->i-j);
        return list.stream().mapToInt(Integer::intValue).toArray();


    }

    int dfs(int x,int y,int m,int n,int[][]land) {
        if(x<0 || x>=m) return 0;
        if (y<0 || y>=n) return 0;
        if(land[x][y]!=0) return 0;
        int area = 1;
        land[x][y] = 999;
        area += dfs(x+1,y,m,n,land);
         area += dfs(x-1,y,m,n,land);
         area += dfs(x,y+1,m,n,land);
         area += dfs(x,y-1,m,n,land);
         area += dfs(x+1,y+1,m,n,land);
        area += dfs(x-1,y-1,m,n,land);

        area += dfs(x+1,y-1,m,n,land);
        area += dfs(x-1,y+1,m,n,land);
        return area;
    }
 
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值