题目:
你有一个用于表示一片土地的整数矩阵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}}; }