[LeetCode 200] 岛屿数量

200. 岛屿数量

dfs

四个方向dfs就行了,走过的地方标0

#include 
#include 
using namespace std;

class Solution {
  public:
    void dfs(int i, int j, vector> &grid) {
        if (i < 0 || j < 0 || i >= grid.size() || j >= grid[i].size() ||
            grid[i][j] == '0')
            return;
        grid[i][j] = '0';
        dfs(i + 1, j, grid);
        dfs(i, j - 1, grid);
        dfs(i - 1, j, grid);
        dfs(i, j + 1, grid);
    }
    int numIslands(vector> &grid) {
        int cnt = 0;
        for (int i = 0; i < grid.size(); i++) {
            for (int j = 0; j < grid[i].size(); j++) {
                if (grid[i][j] == '1') {
                    cnt++;
                    dfs(i, j, grid);
                }
            }
        }
        return cnt;
    }
};

int main() {
    Solution s;
    vector> grid = {{'1', '0', '1', '1', '1'},
                                 {'1', '0', '1', '0', '1'},
                                 {'1', '1', '1', '0', '1'}};

    int res = s.numIslands(grid);
    cout << res;

    return 0;
}

你可能感兴趣的:([LeetCode 200] 岛屿数量)