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:

Given m = 3, n = 3positions = [[0,0], [0,1], [1,2], [2,1]].
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

We return the result as an array: [1, 1, 2, 3]

用一个一维数组来表示 matrix 

定义四个方向,依次检查四个方向

用find 函数来辨别 是否被 union 过

int[][] dirs = new int[][] {{1,0}, {-1, 0}, {0, 1}, {0,-1}};
    public List<Integer> numIslands2(int m, int n, int[][] positions) {
        int[] roots = new int[m * n];
        List<Integer> res = new ArrayList<>();
        if (m == 0 || n == 0) return res;
        int cnt = 0;
        Arrays.fill(roots, -1);
        for (int[] position : positions) {
            int pos = position[0] * n + position[1];
            roots[pos] = pos;
            cnt++;
            for (int[] dir : dirs) {
                int x = position[0] + dir[0];
                int y = position[1] + dir[1];
                int next = x * n + y;
                if (x < 0 || y < 0 || x >= m || y >= n || roots[next] == -1) continue;
                int nextPos = find(roots, next);
                if (pos != nextPos) {   如果 四周其中之一 与 当前位置 pos 不一样,union 
                    roots[pos] = nextPos;
                    pos = nextPos;
                    cnt--;
                }
            }
            res.add(cnt);
        }
        return res;
    }
    public int find(int[] roots, int id) {
        while (roots[id] != id) {
            id = roots[id];
        }
        return id;
    }







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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值