你有一個用於表示一片土地的整數矩陣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; } }