200. Number of Islands

本文介绍了使用深度优先搜索(DFS)算法解决LeetCode上的200.Number of Islands问题,详细解析了如何通过DFS遍历二维网格地图,计算岛屿数量,并提供了一段C++代码实现。

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

本周学习了DFS,因此在LeetCode中挑选了一道关于DFS的题目作为巩固。

题目:200. Number of Islands

Given a 2d grid map of '1's (land) and '0's (water), count 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.

Example 1:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

 

题解:

  这道题是经典的通过DFS求联通块的题目。由于grid中每一个点都有可能是成为发现的新island中的第一个点,于是在主函数(numIslands)中,需要对每一个陆地元素为起点进行DFS。在主函数中的每一次DFS结束之后,说明已经完成了一个岛屿的遍历,因此需要对岛屿总数计数器进行递增。

     对于DFS中的操作,一般而言对于图的DFS遍历,都通过一个visited二维数组来判断这个节点是否遍历过,但是这里由于题目的特性,可以通过将已经遍历过的陆地置0求得。也就是说,在每一次DFS中,将当前节点grid值置零,然后判断这个节点的上下左右邻域是否越界。如果不越界,并且是陆地,就继续DFS递归下去。

class Solution {
public:
    
    void dfs(vector<vector<char>>& grid, int y, int x)
    {
        int rows = grid.size();
        int cols = grid[0].size();
        if(x>=cols || x<0 || y<0 || y>=rows) return; 
        
        grid[y][x] = '0'; //说明已经遍历过了这个节点
        if(x-1>=0 && grid[y][x-1] == '1') dfs(grid,y,x-1);
        if(y-1>=0 && grid[y-1][x] == '1') dfs(grid,y-1,x);
        if(x+1 < cols && grid[y][x+1] =='1') dfs(grid,y,x+1);
        if(y+1 < rows && grid[y+1][x] =='1') dfs(grid,y+1,x);
    }
    
    int numIslands(vector<vector<char>>& grid) {
        if(grid.empty()) return 0;
        
        int totalIsland = 0;
        int rows = grid.size();
        int cols = grid[0].size();

        for(int i = 0 ; i < rows ; i ++)
        {
            for(int j = 0 ; j < cols; j ++)
            {
                if(grid[i][j]=='1')
                {
                   dfs(grid,i,j);  
                   //当每一次完成这样的遍历之后,就说明一个岛已经遍历完
                   totalIsland ++;
                }
            }
        }

        return totalIsland;
    }

};

 

转载于:https://www.cnblogs.com/MT-ComputerVision/p/6579926.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值