Skip to content

Commit 05f1837

Browse files
committed
水域大小
1 parent f50c9e5 commit 05f1837

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
package com.leetcode_cn.medium;
2+
/****************水域大小************/
3+
4+
import java.util.*;
5+
6+
/**
7+
* 你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。
8+
*
9+
* 示例:
10+
*
11+
* 输入:
12+
* [
13+
* [0,2,1,0],
14+
* [0,1,0,1],
15+
* [1,1,0,1],
16+
* [0,1,0,1]
17+
* ]
18+
* 输出: [1,2,4]
19+
* 提示:
20+
*
21+
* 0 < len(land) <= 1000
22+
* 0 < len(land[i]) <= 1000
23+
*
24+
*/
25+
public class PondSizes {
26+
27+
public int[] pondSizes(int[][] land) {
28+
29+
if (land.length == 0) return new int[]{};
30+
int rows = land.length;
31+
int cols = land[0].length;
32+
if (cols == 0) return new int[]{};
33+
List<Integer> results = new ArrayList<>();
34+
35+
for (int i = 0; i < rows; i++) {
36+
for (int j = 0; j < cols; j++) {
37+
if (land[i][j] == 0) {
38+
int index = PondSize(i, j, land);
39+
if (index != 0) {
40+
results.add(index);
41+
}
42+
}
43+
}
44+
}
45+
int[] resultArr = new int[results.size()];
46+
for (int i = 0; i < results.size(); i++) {
47+
resultArr[i] = results.get(i);
48+
}
49+
Arrays.sort(resultArr); // 排序
50+
return resultArr;
51+
}
52+
53+
private int PondSize(int i, int j, int[][] land) {
54+
// 越过边界
55+
if (i < 0 || j < 0 || i >= land.length || j >= land[0].length) return 0;
56+
// 不是池塘
57+
if (land[i][j] != 0) return 0;
58+
// 设置已经访问
59+
land[i][j] = -1;
60+
return 1+
61+
PondSize(i+1, j, land)+// 下
62+
PondSize(i-1, j, land)+// 上
63+
PondSize(i, j+1, land)+// 右
64+
PondSize(i, j-1, land)+// 左
65+
PondSize(i-1, j-1, land)+// 左上
66+
PondSize(i-1, j+1, land)+// 右上
67+
PondSize(i+1, j-1, land)+// 左下
68+
PondSize(i+1, j+1, land);// 右下
69+
70+
}
71+
72+
public static void main(String[] args) {
73+
int[][] land = new int[][]{
74+
{0,2,1,0},
75+
{0,1,0,1},
76+
{1,1,0,1},
77+
{0,1,0,1}
78+
};
79+
int[] result = new PondSizes().pondSizes(land);
80+
System.out.println(Arrays.toString(result));
81+
}
82+
}

0 commit comments

Comments
 (0)