面试题 16.19. 水域大小
你有一个用于表示一片土地的整数矩阵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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/pond-sizes-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
DFS往八个方向搜索,遇到0计数加1,遇到其他则停止。
代码:
class Solution { public int[] pondSizes(int[][] land) { int cnt= 0; ArrayList<Integer> reslist = new ArrayList<>(); for (int i=0;i<land.length; i++) { for (int j=0;j<land[0].length;j++) { if (land[i][j]==0) { cnt = dfs(land,i,j); reslist.add(cnt); } } } int[] res = new int [reslist.size()]; for (int i=0;i<reslist.size();i++) res[i]=reslist.get(i); Arrays.sort(res); return res; } public int dfs(int[][] land,int i,int j) { if (i<0 || i>=land.length || j<0 || j>=land[0].length || land[i][j]!=0) return 0; land[i][j]=-1; int count = 1; count+=dfs(land, i+1, j); count+=dfs(land, i-1, j); count+=dfs(land, i, j+1); count+=dfs(land, i, j-1); count+=dfs(land, i+1, j+1); count+=dfs(land, i-1, j+1); count+=dfs(land, i-1, j-1); count+=dfs(land, i+1, j-1); return count; } }