程序員面試金典-面試題 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}}; 
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM