leetcode 面试题 16.19. 水域大小

class Solution {
    static final int[] dx = {0, 0, -1, 1, -1, 1, 1, -1};
    static final int[] dy = {1, -1, 0, 0, -1, 1, -1, 1};
    boolean[][] visited = new boolean[1005][1005];

    public int[] pondSizes(int[][] land) {
        ArrayList res = new ArrayList();
        for (int i = 0; i < land.length; i++) {
            for (int j = 0; j < land[i].length; j++) {
                int r = dfs(i, j, land);
                if(r>0){
                    res.add(r);
                }
            }
        }
        int[] temp = new int[res.size()];
        int i = 0;
        for (Integer r : res) {
            temp[i++] = r;
        }
        Arrays.sort(temp);
        return temp;
    }

    public int dfs(int i, int j, int[][] land) {
        if (i < 0 || i >= land.length || j < 0 || j >= land[0].length || visited[i][j] || land[i][j] > 0) {
            return 0;
        }
        int count = 1;
        visited[i][j] = true;
        for (int k = 0; k < 8; k++) {
            count += dfs(i + dx[k], j + dy[k], land);
        }
        return count;
    }
}

 

你可能感兴趣的:(leetcode)