c_cpp 200.岛屿数量

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 200.岛屿数量相关的知识,希望对你有一定的参考价值。

struct Coord {
    int x;
    int y;
    Coord(int tmp_x, int tmp_y): x(tmp_x), y(tmp_y) {}
};

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if (grid.empty() || grid.size() == 0 || grid[0].empty() || grid[0].size() == 0) return 0;
        res = 0;
        four_ways = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        
        for (int i = 0; i < grid.size(); i++) {
            for (int j = 0; j < grid[0].size(); j++) {
                if (grid[i][j] == '1') {
                    Coord c(i, j);
                    bfs(grid, c);
                    res++;  
                }
            }
        }
        return res;
    }
    
private:
    int res;
    vector<vector<int>> four_ways;
    void bfs(vector<vector<char>>& grid, Coord& c) {
        queue<Coord> Q;
        Q.push(c);
        grid[c.x][c.y] = '0';
        while(!Q.empty()) {
            Coord cur_c = Q.front(); Q.pop();
            for (int i = 0; i < 4; i++) {
                Coord new_c(cur_c.x + four_ways[i][0], cur_c.y + four_ways[i][1]);
                if (is_valid(grid, new_c)) {
                    Q.push(new_c);
                    grid[new_c.x][new_c.y] = '0';
                }
            }
        }
    }
    bool is_valid(vector<vector<char>>& grid, Coord& c) {
        if (c.x < 0 || c.x >= grid.size() || c.y < 0 || c.y >= grid[0].size() || grid[c.x][c.y] == '0') {
            return false;
        }
        return true;
    }
};

以上是关于c_cpp 200.岛屿数量的主要内容,如果未能解决你的问题,请参考以下文章

力扣 200. 岛屿数量

力扣 200. 岛屿数量

200.岛屿数量

LeetCode 200. 岛屿数量

200. 岛屿数量

岛屿数量(力扣第200题)