首页 > 编程语言 >#yyds干货盘点# LeetCode程序员面试金典:水域大小

#yyds干货盘点# LeetCode程序员面试金典:水域大小

时间:2023-03-03 18:32:16浏览次数:34  
标签:yyds land int 金典 list num result findPool LeetCode

题目:

你有一个用于表示一片土地的整数矩阵land,该矩阵中每个点的值代表对应地点的海拔高度。若值为0则表示水域。由垂直、水平或对角连接的水域为池塘。池塘的大小是指相连接的水域的个数。编写一个方法来计算矩阵中所有池塘的大小,返回值需要从小到大排序。

示例:

输入:

[

 [0,2,1,0],

 [0,1,0,1],

 [1,1,0,1],

 [0,1,0,1]

]

输出: [1,2,4]

代码实现:

class Solution {
public int[] pondSizes(int[][] land) {
List<Integer> list = new ArrayList<>();
int temp;

// 遍历矩阵每个元素
for (int i = 0; i < land.length; i++) {
for (int j = 0; j < land[0].length; j++) {
temp = findPool(land, i, j);
if (temp != 0) list.add(temp);
}
}

// 第一种List<Integer>转int[]
// int[] result = new int[list.size()];
// for (int i = 0; i < result.length; i++) {
// result[i] = list.get(i);
// }

// 第二种List<Integer>转int[],优雅且高效
int[] result = list.stream().mapToInt(Integer::valueOf).toArray();

Arrays.sort(result);

return result;
}

private int findPool(int[][] land, int x, int y) {
int num = 0;
if (x < 0 || x >= land.length || y < 0 ||y>=land[0].length||land[x][y]!=0) {
return num;
}
num++;
land[x][y] = -1; // 如果为0,就转换为-1,避免重复搜索

num += findPool(land, x + 1, y);
num += findPool(land, x - 1, y);
num += findPool(land, x, y + 1);
num += findPool(land, x, y - 1);
num += findPool(land, x + 1, y + 1);
num += findPool(land, x + 1, y - 1);
num += findPool(land, x - 1, y + 1);
num += findPool(land, x - 1, y - 1);

return num;
}
}

标签:yyds,land,int,金典,list,num,result,findPool,LeetCode
From: https://blog.51cto.com/u_13321676/6099088

相关文章