【LeetCode 面试经典150题】200. Number of Islands 岛屿数量

本文介绍了一种解决给定二维二进制网格中计算岛屿数量问题的方法,通过深度优先搜索(DFS)遍历网格,标记已访问的陆地区域,统计未访问的1节点形成的不同岛屿数量。
摘要由CSDN通过智能技术生成

200. Number of Islands(岛屿数量)

题目大意

Given an m x n 2D binary grid grid which represents a map of '1’s (land) and '0’s (water), return the number of islands.

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.

中文释义

给定一个 m x n 的二维二进制网格 grid,它代表了由 ‘1’(陆地)和 ‘0’(水域)构成的地图,返回岛屿的数量。

一个岛屿被水包围,并且是通过水平或垂直连接相邻的陆地形成的。你可以假设网格的所有四个边界都被水包围。

示例

  • 示例 1:
    • 输入:grid = [["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]
    • 输出:1
  • 示例 2:
    • 输入:grid = [["1","1","0","0","0"],["1","1","0","0","0"],["0","0","1","0","0"],["0","0","0","1","1"]]
    • 输出:3

限制条件

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 300
  • grid[i][j] 是 ‘0’ 或 ‘1’。

解题思路

使用深度优先搜索(DFS)来解决问题。遍历网格,对每个未访问的 ‘1’ 节点执行 DFS 搜索,以找出岛屿的边界。

步骤说明

  1. 初始化一个标记节点是否已访问的二维布尔数组 is_visited
  2. 对网格中的每个节点进行遍历:
    • 如果节点是 ‘1’ 且未被访问,则执行 DFS。
    • DFS 会标记所有与当前节点相连的 ‘1’ 节点为已访问。
  3. 每次执行 DFS 时,岛屿数量增加。
  4. 返回岛屿的总数量。

代码

class Solution {
public:
    void dfs(int i, int j, vector<vector<char>>& grid, vector<vector<bool>>& is_visited) {
        if (i < 0 || i >= grid.size() || j < 0 || j >= grid[i].size()) return;
        if (is_visited[i][j] || grid[i][j] == '0') return;

        is_visited[i][j] = true;
        dfs(i - 1, j, grid, is_visited);
        dfs(i + 1, j, grid, is_visited);
        dfs(i, j - 1, grid, is_visited);
        dfs(i, j + 1, grid, is_visited);
    }

    int numIslands(vector<vector<char>>& grid) {
        int ans = 0;
        int n = grid.size(), m = grid[0].size();
        vector<vector<bool>> is_visited(n, vector<bool>(m, false));

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == '1' && !is_visited[i][j]) {
                    dfs(i, j, grid, is_visited);
                    ans++;
                }
            }
        }
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值