Leetcode 200.岛屿的数量 - DFS、BFS

Leetcode 200 岛屿的数量:

DFS利用函数调用栈保证了检索顺序,

BFS则需要自己建立队列,把待检索对象按规则入队。

class Solution {  // DFS解法,8ms/10.7MB,99.7% / 92%
public:

    /**
    * row,col: 坐标,以0开始.
    * 用row和col,而不是x,y. 否则容易写成grid[x][y],顺序不对!!
    */
    void dfs_set_zero(vector<vector<char>>& grid, int row, int col) {
        int n_rows = grid.size();
        if (!n_rows) return;
        int n_cols = grid[0].size();
        if (!n_cols) return;

        if (row<0 || row>=n_rows || col<0 || col>=n_cols) return;

        if (grid[row][col] == '1') {
            grid[row][col] = '0';
            dfs_set_zero(grid, row-1, col);
            dfs_set_zero(grid, row+1, col);
            dfs_set_zero(grid, row, col-1);
            dfs_set_zero(grid, row, col+1);
        }
    }

    int numIslands(vector<vector<char>>& grid) {
        int result = 0;
        for (int i=0; i<grid.size(); ++i) {
            for (int j=0; j<grid[0].size(); ++j) {
                if (grid[i][j] == '1') {
                    result++;
                    dfs_set_zero(grid, i, j);
                }
            }
        }
        return result;
    }
};
class Solution {  // BFS解法,12ms/11MB, 96.9% / 69.4%
public:
    queue<pair<int,int>> q;

    void bfs_set_zero(vector<vector<char>>& grid) {
        int n_rows = grid.size();
        if(!n_rows) return;
        int n_cols = grid[0].size();
        if(!n_cols) return;

        while (!q.empty()) {
            auto pos = q.front();
            q.pop();
            if (grid[pos.first][pos.second] == '1') {
                grid[pos.first][pos.second] = '0';
                if (pos.first-1>=0 && grid[pos.first-1][pos.second] == '1')
                    q.emplace(pos.first-1,pos.second);
                if (pos.first+1<n_rows && grid[pos.first+1][pos.second] == '1')
                    q.emplace(pos.first+1,pos.second);
                if (pos.second-1>=0 && grid[pos.first][pos.second-1] == '1')
                    q.emplace(pos.first,pos.second-1);
                if (pos.second+1<n_cols && grid[pos.first][pos.second+1] == '1')
                    q.emplace(pos.first,pos.second+1);
            }
        }
    }

    int numIslands(vector<vector<char>>& grid) {
        int result = 0;
        for (int i=0; i<grid.size(); i++) {
            for (int j=0; j<grid[0].size(); j++) {
                if (grid[i][j] == '1') {
                    result++;
                    //q.push(make_pair(i,j));
                    q.emplace(i,j);  // 使用emplace而非push,constructed in-place
                    bfs_set_zero(grid);
                }
            }
        }
        return result;
    }
};

原文地址:https://www.cnblogs.com/dylanchu/p/11326423.html

时间: 2024-11-05 22:41:23

Leetcode 200.岛屿的数量 - DFS、BFS的相关文章

leetcode 200. 岛屿数量(dfs||bfs)

给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量.一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的.你可以假设网格的四个边均被水包围. 示例 1: 输入:11110110101100000000 输出: 1示例 2: 输入:11000110000010000011 输出: 3 来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/number-of-islands class Solution { pu

LeetCode | 200. 岛屿数量

原题(Medium): 给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格,计算岛屿的数量.一个岛被水包围,并且它是通过水平方向或垂直方向上相邻的陆地连接而成的.你可以假设网格的四个边均被水包围. 思路:递归 这题类型跟我们之前做过的一题单词搜索类似.所以我在看到这题之后,就想到了可以用与之相同的思路:建立一个代表搜索方向的数组,在当前坐标下,如果往某个方向移动一格是符合一定条件的,就往该方向移动一格,且是递归形式的移动.在这里条件就是不超越边界,且该方向上有岛屿可供移动,且是未被访问过

leetcode 200. Number of Islands(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

[LeetCode] 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

[LeetCode] 126. Word Ladder II_Hard tag: BFS&amp;DFS

Given two words (beginWord and endWord), and a dictionary's word list, find all shortest transformation sequence(s) from beginWord to endWord, such that: Only one letter can be changed at a time Each transformed word must exist in the word list. Note

leetcode 261-Graph Valid Tree(medium)(BFS, DFS, Union find)

Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree. 这道题主要就是判断1.是否有环路 2. 是否是连通图 可以用DFS, BFS 和 Union find,union find最合适. 对于DFS和BFS,首先都是建立

Dfs/Bfs/记忆化搜索问题 | 问题集合

写在前面 动归和搜索似乎我打得特憋懒. 可能是因为搜索打的太少了??? 然后之前做过的一些题我就不再写了,比如填涂颜色/海战啥的? 然后每一题打两种解法(:Dfs/Bfs 前提是在题目里两种都能A P1596 湖计数 题目描述 Due to recent rains, water has pooled in various places in Farmer John's field, which is represented by a rectangle of N x M (1 <= N <=

[LeetCode] 130. Surrounded Regions_Medium tag: DFS

Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. Example: X X X X X O O X X X O X X O X X After running your function, the bo

Leetcode之深度优先搜索(DFS)专题-547. 朋友圈(Friend Circles)

Leetcode之深度优先搜索(DFS)专题-547. 朋友圈(Friend Circles) 深度优先搜索的解题详细介绍,点击 班上有 N 名学生.其中有些人是朋友,有些则不是.他们的友谊具有是传递性.如果已知 A 是 B 的朋友,B 是 C 的朋友,那么我们可以认为 A 也是 C 的朋友.所谓的朋友圈,是指所有朋友的集合. 给定一个 N * N 的矩阵 M,表示班级中学生之间的朋友关系.如果M[i][j] = 1,表示已知第 i 个和 j 个学生互为朋友关系,否则为不知道.你必须输出所有学生