本文共 1144 字,大约阅读时间需要 3 分钟。
Difficulty: 中等
你有一个用于表示一片土地的整数矩阵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
Language: 全部题目
class Solution { public int[] pondSizes(int[][] land) { Listlist = new ArrayList<>(); int m = land.length, n = land[0].length; for(int i=0;i 0) list.add(area); } } list.sort((i,j)->i-j); return list.stream().mapToInt(Integer::intValue).toArray(); } int dfs(int x,int y,int m,int n,int[][]land) { if(x<0 || x>=m) return 0; if (y<0 || y>=n) return 0; if(land[x][y]!=0) return 0; int area = 1; land[x][y] = 999; area += dfs(x+1,y,m,n,land); area += dfs(x-1,y,m,n,land); area += dfs(x,y+1,m,n,land); area += dfs(x,y-1,m,n,land); area += dfs(x+1,y+1,m,n,land); area += dfs(x-1,y-1,m,n,land); area += dfs(x+1,y-1,m,n,land); area += dfs(x-1,y+1,m,n,land); return area; } }
转载地址:http://juyzi.baihongyu.com/