LeetCode #305 - Number of Islands II

本文介绍了一种使用并查集数据结构解决动态岛屿数量计算问题的方法。在一个初始充满水的二维网格上,通过一系列操作将水域转换为陆地,并在每次操作后计算岛屿的数量。文章详细解释了算法原理,包括如何初始化并查集、执行查找和合并操作,以及如何更新岛屿数量。

题目描述:

A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example:

Input: m = 3, n = 3, positions = [[0,0], [0,1], [1,2], [2,1]]

Output: [1,1,2,3]

Explanation:

Initially, the 2d grid grid is filled with water. (Assume 0 represents water and 1 represents land).

0 0 0

0 0 0

0 0 0

Operation #1: addLand(0, 0) turns the water at grid[0][0] into a land.

1 0 0

0 0 0   Number of islands = 1

0 0 0

Operation #2: addLand(0, 1) turns the water at grid[0][1] into a land.

1 1 0

0 0 0   Number of islands = 1

0 0 0

Operation #3: addLand(1, 2) turns the water at grid[1][2] into a land.

1 1 0

0 0 1   Number of islands = 2

0 0 0

Operation #4: addLand(2, 1) turns the water at grid[2][1] into a land.

1 1 0

0 0 1   Number of islands = 3

0 1 0

Follow up:

Can you do it in time complexity O(k log mn), where k is the length of the positions?

由于可以在中途增加点,可能会导致两个小岛连接成一个岛,所以最好的方法是并查集。

class Solution {
public:
    vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {
        int count=0;
        vector<int> result;
        unordered_map<int,int> parent;
        vector<pair<int,int>> dirs={{1,0},{-1,0},{0,1},{0,-1}};
        vector<vector<int>> grid(m,vector<int>(n,0));
        for(auto position:positions)
        {
            int i=position.first, j=position.second;
            grid[i][j]=1;
            int id=i*n+j;//坐标(i,j)表示在grid中是第i*n(列数)+j个点
            parent[id]=id;//初始化根等于自己
            count++; //加入一个1时,就可以先认为加入了一个岛
            for(auto dir:dirs)
            {
                int x=i+dir.first, y=j+dir.second;
                if(x<0||x>=m||y<0||y>=n) continue;
                if(grid[x][y]==0) continue;
                int cur_id=x*n+y;
                if(find(parent,id)!=find(parent,cur_id))
                { //一旦发现当前加入的1和周围1的根不同,说明加入当前1导致两个不连通的岛合并了,所以count减一
                    count--;
                    uni(parent,id,cur_id);
                }
            }
            result.push_back(count);
        }
        return result;
    }
    
    int find(unordered_map<int,int>& parent, int x)
    {
        if(parent[x]==x) return x;
        else return find(parent,parent[x]);
    }
    
    void uni(unordered_map<int,int>& parent, int a, int b)
    {
        int x=find(parent,a);
        int y=find(parent,b);
        parent[x]=y;
    }
};

 

这段代码是 LeetCode 官方题解中用于解决 **“岛屿数量”(Number of Islands)** 问题的深度优先搜索(DFS)实现。其核心目的是通过 DFS 遍历二维字符数组 `grid`,将所有与某个 `&#39;1&#39;` 相连的陆地格子标记为已访问(即设为 `&#39;0&#39;`),从而统计出不相连的岛屿数量--- ### ✅ 函数解析 ```cpp void dfs(vector<vector<char>>& grid, int r, int c) { int nr = grid.size(); int nc = grid[0].size(); grid[r][c] = &#39;0&#39;; // 标记当前格子为已访问 if (r - 1 >= 0 && grid[r - 1][c] == &#39;1&#39;) dfs(grid, r - 1, c); // 上 if (r + 1 < nr && grid[r + 1][c] == &#39;1&#39;) dfs(grid, r + 1, c); // 下 if (c - 1 >= 0 && grid[r][c - 1] == &#39;1&#39;) dfs(grid, r, c - 1); // 左 if (c + 1 < nc && grid[r][c + 1] == &#39;1&#39;) dfs(grid, r, c + 1); // 右 } ``` #### 功能说明: - **参数:** - `vector<vector<char>>& grid`: 输入的二维网格,表示地图。 - `int r, int c`: 当前遍历的格子坐标(行和列)。 - **作用:** - 从 `(r, c)` 开始进行深度优先搜索,将所有相邻的 `&#39;1&#39;`(陆地)都标记为 `&#39;0&#39;`(已访问)。 - 这样可以确保每次遇到一个新的未被访问的 `&#39;1&#39;` 时,它一定是一个新岛屿的一部分。 - **方向处理:** - 检查四个方向(上、下、左、右)是否有 `&#39;1&#39;`,若有,则递归调用 `dfs`。 --- ### 📌 补充说明 - 在主函数 `numIslands` 中,会逐个扫描每个格子: - 如果发现一个 `&#39;1&#39;`,则认为这是一个新岛屿- 调用 `dfs` 将该岛屿的所有连接部分标记为 `&#39;0&#39;`; - 最终统计所有这样的岛屿数量--- ### ✅ 示例输入输出 #### 输入: ```cpp grid = { {&#39;1&#39;,&#39;1&#39;,&#39;0&#39;,&#39;0&#39;,&#39;0&#39;}, {&#39;1&#39;,&#39;1&#39;,&#39;0&#39;,&#39;0&#39;,&#39;0&#39;}, {&#39;0&#39;,&#39;0&#39;,&#39;1&#39;,&#39;0&#39;,&#39;0&#39;}, {&#39;0&#39;,&#39;0&#39;,&#39;0&#39;,&#39;1&#39;,&#39;1&#39;} }; ``` #### 输出: ``` 3 ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值