[LeetCode] 面试题 16.19. 水域大小

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

示例:

输入:
[
[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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/pond-sizes-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这是属于 flood fill 那一类的题。这里我分享一个 BFS 的做法。唯一需要注意的细节是这道题里池塘的定义是八个方向,以及需要对最后的结果先排序再输出。

时间O(mn)

空间O(mn) - 最坏情况下只有一个池塘,即整个池塘,所以所有的点都会在queue内走一遍

Java实现

 1 class Solution {
 2     int m;
 3     int n;
 4     int[] dx = {-1, -1, -1, 0, 0, 1, 1, 1};
 5     int[] dy = {1, 0, -1, 1, -1, 1, 0, -1};
 6     List<Integer> list;
 7 
 8     public int[] pondSizes(int[][] land) {
 9         m = land.length;
10         n = land[0].length;
11         list = new ArrayList<>();
12         for (int i = 0; i < m; i++) {
13             for (int j = 0; j < n; j++) {
14                 if (land[i][j] == 0) {
15                     int count = bfs(land, i, j);
16                     list.add(count);
17                 }
18             }
19         }
20         int n = list.size();
21         int[] res = new int[n];
22         for (int i = 0; i < n; i++) {
23             res[i] = list.get(i);
24         }
25         Arrays.sort(res);
26         return res;
27     }
28 
29     private int bfs(int[][] land, int i, int j) {
30         int count = 1;
31         land[i][j] = -1;
32         Queue<int[]> queue = new LinkedList<>();
33         queue.offer(new int[] { i, j });
34         while (!queue.isEmpty()) {
35             int[] cur = queue.poll();
36             int x = cur[0];
37             int y = cur[1];
38             for (int k = 0; k < 8; k++) {
39                 int newX = x + dx[k];
40                 int newY = y + dy[k];
41                 if (newX >= 0 && newX < m && newY >= 0 && newY < n && land[newX][newY] == 0) {
42                     land[newX][newY] = -1;
43                     count++;
44                     queue.offer(new int[] { newX, newY });
45                 }
46             }
47         }
48         return count;
49     }
50 }

 

LeetCode 题目总结

posted @ 2023-06-22 06:38  CNoodle  阅读(19)  评论(0编辑  收藏  举报