zoukankan      html  css  js  c++  java
  • 程序员面试金典-面试题 16.19. 水域大小

    题目:

    你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。

    示例:

    输入:
    [
      [0,2,1,0],
      [0,1,0,1],
      [1,1,0,1],
      [0,1,0,1]
    ]
    输出: [1,2,4]

    分析:

    由于对角线连的0也算是水域,需要搜索八个方向,且访问过的要标记。

    程序:

    class Solution {
        public int[] pondSizes(int[][] land) {
            m = land.length;
            n = land[0].length;
            visit = new int [m][n];
            List<Integer> res = new ArrayList<>();
            for(int i = 0; i < m; i++){
                for(int j = 0; j < n; ++j){
                    int size = dfs(land, i, j);
                    if(size > 0)
                        res.add(size);
                }
            }
            Collections.sort(res);
            int[] ans = new int[res.size()];
            for(int i = 0; i < res.size(); ++i)
                ans[i] = res.get(i);
            return ans;
        }
        private int dfs(int[][] land, int x, int y){
            if(x < 0 || x >= m || y < 0 || y >= n || land[x][y] > 0 || visit[x][y] == 1)
                return 0;
            visit[x][y] = 1;
            int res = 1;
            for(int i = 0; i < 8; ++i){
                int nx = x + move[i][0];
                int ny = y + move[i][1];
                res += dfs(land, nx, ny);
            }
            return res;
        }
        private int[][] visit;
        int m;
        int n;
        private int[][] move = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1}}; 
    }
  • 相关阅读:
    asp搜索两个以上的词的原理
    ASP连接MYSQL数据库
    一个用ASP生成html的新方法
    文本框随文本的长度而增长
    ASP实现https和http之间转化
    ASP根据IP来判断跳转页面
    Access数据库在线压缩的实现方法
    aspjpeg 半透明描边的实现函数
    Session对象的集合
    react tsx
  • 原文地址:https://www.cnblogs.com/silentteller/p/12518139.html
Copyright © 2011-2022 走看看