200. Number of Islands(DFS or BFS)

本文介绍了一种使用深度优先搜索(DFS)和广度优先搜索(BFS)算法来解决二维矩阵中岛屿数量计算的问题。通过遍历矩阵并标记已访问过的陆地单元格,实现了高效求解。具体包括两种算法的实现代码及示例。

一、问题描述

写在前面:深度优先搜索和广度优先搜索在实际问题中的应用,特别是在矩阵上的BFS和DFS的应用。

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解法:只要先找到一个’1’,然后往它的四个方向递归,递归过程遇到’1’就将其置为‘0’,这样,找完一个“岛”之后,所有在同一个“岛”上的‘1’就全被置为‘0’了,这样,在O(n3)的时间内能找出所有“岛”,因为DFS的时间复杂度为O(n)

class Solution {
public:
    int numIslands(vector<vector<char> >& grid) {
        if(grid.size() == 0) return 0;
        int count = 0;
        for(int i = 0; i < grid.size(); i++) {
            for(int j = 0; j < grid[0].size(); j++) {
                if(grid[i][j] == '1') {
                    count++;
                    BFS(grid, i, j);
                }
            }
        }
        return count;

    }

private:
    bool valid(vector<vector<char> >& grid, int x, int y) {
        return (x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size() && grid[x][y] == '1');
    }
    void BFS(vector<vector<char> >& grid, int x, int y) {
        grid[x][y] = '0';
        if(valid(grid, x-1, y)) BFS(grid, x-1, y);
        if(valid(grid, x, y+1)) BFS(grid, x, y+1);
        if(valid(grid, x+1, y)) BFS(grid, x+1, y);
        if(valid(grid, x, y-1)) BFS(grid, x, y-1);
    }
};

BFS解法:类似的,只要先找到一个’1’,将其上下左右可能的相邻的‘1’入队,接着按照队里的‘1’去找其相邻的‘1’,将找到的相邻的‘1’置为‘0’,只要队里为空,即“岛”增加一个。

class Solution{
public:
    int numIslands(vector<vector<char>> &grid) {
        if(grid.size() == 0 || grid[0].size() == 0)
            return 0;
            int res = 0;
            for(int i = 0; i < grid.size(); ++ i)
                for(int j = 0; j < grid[0].size(); ++ j)
                     if(grid[i][j] == '1'){
                         ++ res;
                         BFS(grid, i, j);
                 }
             return res;
     }
private:
    void BFS(vector<vector<char>> &grid, int x, int y){
        queue<vector<int>> q;
        q.push({x, y});
        grid[x][y] = '0';

         while(!q.empty()){
             x = q.front()[0], y = q.front()[1];
             q.pop();

             if(x > 0 && grid[x - 1][y] == '1'){
                 q.push({x - 1, y});
                 grid[x - 1][y] = '0';
             }
             if(x < grid.size() - 1 && grid[x + 1][y] == '1'){
                 q.push({x + 1, y});
                 grid[x + 1][y] = '0';
             }
             if(y > 0 && grid[x][y - 1] == '1'){
                 q.push({x, y - 1});
                 grid[x][y - 1] = '0';
             }
             if(y < grid[0].size() - 1 && grid[x][y + 1] == '1'){
                 q.push({x, y + 1});
                 grid[x][y + 1] = '0';
             }
         }
     }
};
### 关于 DFSBFS 的练习题及学习资料 #### 经典练习题推荐 1. **洛谷平台上的经典题目** 可以通过洛谷平台找到许多经典的 DFSBFS 题目。例如,引用中的【XR-2】奇迹 - 洛谷是一个很好的例子[^2]。该题目涉及 BFS 的应用,适合初学者理解广度优先搜索的核心思想。 2. **LeetCode 平台上的相关题目** LeetCode 提供了许多与图遍历相关的题目,以下是几个典型题目: - **岛屿数量 (Number of Islands)**:这是一道典型的 BFS/DFS 应用题,目标是计算二维网格中由 '1' 表示的连通区域的数量。 ```python from collections import deque def numIslands(grid): if not grid or not grid[0]: return 0 rows, cols = len(grid), len(grid[0]) visited = [[False]*cols for _ in range(rows)] islands = 0 def bfs(r, c): queue = deque([(r, c)]) while queue: row, col = queue.popleft() directions = [(row-1,col),(row+1,col),(row,col-1),(row,col+1)] for dr, dc in directions: if 0<=dr<rows and 0<=dc<cols and not visited[dr][dc] and grid[dr][dc]=='1': visited[dr][dc]=True queue.append((dr,dc)) for r in range(rows): for c in range(cols): if grid[r][c] == '1' and not visited[r][c]: visited[r][c] = True bfs(r, c) islands += 1 return islands ``` 3. **二叉树合并问题** 使用队列实现的二叉树合并问题是另一个不错的 BFS 实践案例[^3]。此问题可以通过迭代方式解决,非常适合用来巩固对队列操作的理解。 #### 学习资源推荐 1. **书籍推荐** 对于深入学习 DFSBFS,可以参考《算法导论》的相关章节。这本书详细介绍了这两种搜索策略及其应用场景,并提供了丰富的伪代码实例。 2. **在线课程** Coursera 上有斯坦福大学开设的数据结构与算法专项课程,其中专门讲解了图的遍历技术,包括 DFSBFS 的原理和实践技巧[^1]。 3. **博客文章** 许多编程博主分享了自己的经验总结,比如如何选择合适的场景使用 DFS 或者 BFS。这些文章通常附带详细的代码解析和实际案例分析。 #### 总结 无论是理论学习还是实战演练,掌握好 DFSBFS 是非常重要的。建议从简单的模板题入手逐步过渡到复杂的应用场景,同时不断积累解题思路并优化自己的编码能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值