水域大小(Java)

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


package com.loo;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class PondAreaSize {
    // 当前坐标对应的八个方向
    public static int[] dirX = new int[] {0 , 1 , 1 , 1 , 0 , -1 , -1 , -1};
    public static int[] dirY = new int[] {1 , 1 , 0 , -1 , -1 , -1 , 0 , 1};

    public static void main(String[] args) {
        int[][] land = new int[][] {
                {0,2,1,0},
                {0,1,0,1},
                {1,1,0,1},
                {0,1,0,1}
        };
        Integer[] pondArea = getPondAreaSize(land);
        System.out.println(Arrays.toString(pondArea));
    }
    
    public static Integer[] getPondAreaSize(int[][] pond) {
        int count = 0;
        List<Integer> list = new ArrayList<Integer>();
        for (int i=0;i<pond.length;i++) {
            for (int j=0;j<pond[0].length;j++) {
                count = findRoundPond(pond , i , j);
                if (count!=0) {
                    list.add(count);
                }
            }
        }
        Integer[] result = list.toArray(new Integer[list.size()]);
        Arrays.sort(result);
        return result;
    }
    // 遍历矩阵,遇到0之后就开始搜索周围是否还有0,搜索过程递归的返回条件就是pond[x][y] != 0或索引x和y越界。
        // 为了避免在递归的时候重复判断矩阵中的0,因为在判断池塘个数的过程中,每个0只会被记录一次,记录完之后就没有价值了,所以可以在判断为0后加上pond[x][y] = -1,这样在下次dfs的时候就可以避免重复的0。
    public static int findRoundPond(int[][] pond , int x , int y) {
        int count = 0;
        if (x<0 || x>=pond.length || y<0 || y>=pond[0].length || pond[x][y]!=0) {
            return count;
        }
        count++;
        pond[x][y] = -1;
        for (int i=0;i<dirX.length;i++) {
            int dx = x + dirX[i];
            int dy = y + dirY[i];
            count += findRoundPond(pond , dx , dy);
        }
        return count;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值