Number of Islands II

本文介绍了一种使用Java实现的岛屿计数算法,该算法通过输入一个二维网格地图及一系列放置岛屿的位置坐标来动态更新并返回当前存在的独立岛屿数量。算法运用了并查集的数据结构来高效地判断和合并相邻的岛屿。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 public class Solution {
 2     private int count;
 3     private int[] parent;
 4     public List<Integer> numIslands2(int m, int n, int[][] positions) {
 5         List<Integer> result = new ArrayList<>();
 6         if (positions.length == 0) {
 7             return result;
 8         }
 9         parent = new int[m*n];
10         int[][] islands = new int[m][n];
11         count = 0;
12         
13         for (int i = 0; i < parent.length; i++) {
14             parent[i] = i;
15         }
16 
17         for (int[] position : positions) {
18             int x = position[0];
19             int y = position[1];
20             islands[x][y] = 1;
21             count++;
22             
23             if (x > 0 && islands[x - 1][y] == 1) {
24                 union(x*n + y, (x - 1)*n + y);
25             }
26             
27             if (x < m - 1 && islands[x + 1][y] == 1) {
28                 union(x*n + y, (x + 1)*n + y);
29             }
30             
31             if (y > 0 && islands[x][y - 1] == 1) {
32                 union(x*n + y, x * n + y - 1);
33             }
34             
35             if (y < n - 1 && islands[x][y + 1] == 1) {
36                 union(x*n + y, x * n + y + 1);
37             }
38             result.add(count);
39         }
40         return result;
41     }
42     
43     private void union(int a, int b) {
44         int indexA = findParent(a);
45         int indexB = findParent(b);
46         if (indexA != indexB) {
47             count--;
48             parent[indexA] = parent[indexB];
49         }
50     }
51     
52     private int findParent(int x) {
53         while (x != parent[x]) {
54             parent[x] = parent[parent[x]];
55             x = parent[x];
56         }
57         return x;
58     }
59 }

 

转载于:https://www.cnblogs.com/shuashuashua/p/5645599.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值