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