zoukankan      html  css  js  c++  java
  • leetcode——16.19.水域大小

    public int[] pondSizes(int[][] land) {
            List<Integer> list = new ArrayList<>();
            int temp;
            for (int i = 0; i < land.length; i++) {
                for (int j = 0; j < land[0].length; j++) {
                    temp = findpond(land, i, j);
                    if (temp != 0) {
                        list.add(temp);
                    }
                }
            }
            int[] result = list.stream().mapToInt(Integer::valueOf).toArray();
            Arrays.sort(result);
            return result;
        }
    
        private int findpond(int[][] land, int i, int j) {
            int sum = 0;
            if (i < 0 || i >= land.length || j < 0 || j >= land[0].length || land[i][j] != 0) {
                return sum;
            }
            land[i][j] = -1;
            sum++;
            sum += findpond(land, i + 1, j);
            sum += findpond(land, i, j + 1);
            sum += findpond(land, i - 1, j);
            sum += findpond(land, i, j - 1);
            sum += findpond(land, i + 1, j + 1);
            sum += findpond(land, i - 1, j - 1);
            sum += findpond(land, i + 1, j - 1);
            sum += findpond(land, i - 1, j + 1);
            return sum;
        }

     依然是别人的题解,自己看懂写了一遍。

    对于DFS和递归还是不熟练,很多地方就想不到,命名也是不难的东西。

    这里面将Arraylist转化为list的这个语句

    int[] result = list.stream().mapToInt(Integer::valueOf).toArray();

    多妙啊,对stream()与lambda的用法尚且不会,有待学习。

    对list进行排序,我还傻傻地写了冒泡排序,实际上一句话就可以搞定啊:

    Arrays.sort(result);

    多神奇啊,这还是刷题刷得不够多的原因,要继续加油啊。

    像这道题,思路多清楚。遍历矩阵,遇到非零元素,就返回结果为0.遇到代表池塘的0,就将该元素标记为-1,可以避免重复搜索,并且在8个方向上进行统计池塘面积。

    多妙啊!!!!

    ——2020.6.21

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    Excel—TIME函数简介与用法
    Excel—LEFT、RIGHT、MID函数提取不同位置的字段
    $scope.triggerSave $scope.createForm.dayType.$dirty = false;
    SVN clean up的作用
    js 获取当年到今日的时间区间
    jersey
    vector
    AngularJS 2
    URL 字符介绍
    JS factory
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/13171655.html
Copyright © 2011-2022 走看看