题号:no79
题目名:水域大小
原题URL:https://leetcode-cn.com/problems/pond-sizes-lcci/
题目描述
你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。
示例
示例 1:
输入:
[
[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
思路
1.dfs和bfs都可以,这种扩散题我习惯用bfs
2.套用标准bfs模板,如果当前值是水域,向四周扩散,一定要注意的是,每次扩散的时候要先进行标记,否则会重复扩散,比如左下,下都有的时候,如果不加入队列的时候就做标机,就会导致当前结点标记了左下和下,遍历到出栈左下的时候又会遍历下,这里一定要注意
3.排序数组
解题代码
List<Integer> list = new ArrayList<>();
public int[] pondSizes(int[][] land) {
//遍历水池
for (int i = 0; i < land.length; i++) {
for (int j = 0; j < land[i].length; j++) {
//当前地区为水域
if(land[i][j]==0) {
int count = 0;
Deque<int[]> queue = new ArrayDeque<> ();
queue.add(new int[]{i,j});
while (!queue.isEmpty()) {
int size = queue.size();
while (size > 0) {
//移除结点
int[] ints = queue.removeFirst();
//将结点位置标记为统计过
land[ints[0]][ints[1]] = -1;
//统计水域
count++;
//左上
if(ints[0]-1>=0&&ints[1]-1>=0&&land[ints[0]-1][ints[1]-1]==0) {
queue.addLast(new int[]{ints[0]-1,ints[1]-1});
land[ints[0]-1][ints[1]-1] = -2;
}
//上边
if(ints[0]-1>=0&&land[ints[0]-1][ints[1]]==0) {
queue.addLast(new int[]{ints[0]-1,ints[1]});
land[ints[0]-1][ints[1]] = -2;
}
//右上
if(ints[0]-1>=0&&ints[1]+1<=land[0].length-1&&land[ints[0]-1][ints[1]+1]==0) {
queue.addLast(new int[]{ints[0]-1,ints[1]+1});
land[ints[0]-1][ints[1]+1] = -2;
}
//左边
if(ints[1]-1>=0&&land[ints[0]][ints[1]-1]==0) {
queue.addLast(new int[]{ints[0],ints[1]-1});
land[ints[0]][ints[1]-1] = -2;
}
//右边
if(ints[1]+1<=land[0].length-1&&land[ints[0]][ints[1]+1]==0) {
queue.addLast(new int[]{ints[0],ints[1]+1});
land[ints[0]][ints[1]+1] = -2;
}
//左下
if(ints[0]+1<=land.length-1&&ints[1]-1>=0&&land[ints[0]+1][ints[1]-1]==0) {
queue.addLast(new int[]{ints[0]+1,ints[1]-1});
land[ints[0]+1][ints[1]-1] = -2;
}
//下边
if(ints[0]+1<=land.length-1&&land[ints[0]+1][ints[1]]==0) {
queue.addLast(new int[]{ints[0]+1,ints[1]});
land[ints[0]+1][ints[1]] = -2;
}
//右下
if(ints[0]+1<=land.length-1&&ints[1]+1<=land[0].length-1&&land[ints[0]+1][ints[1]+1]==0) {
queue.addLast(new int[]{ints[0]+1,ints[1]+1});
land[ints[0]+1][ints[1]+1] = -2;
}
size--;
}
}
list.add(count);
}
}
}
int[] res = new int[list.size()];
for (int i = 0; i < res.length; i++) {
res[i] = list.get(i);
}
Arrays.sort(res);
return res;
}