Leetcode刷题笔记题解(C++):200. 岛屿数量

思路:利用深度优先搜索的思路来查找1身边的1,并且遍历之后进行0替换防止重复dfs,代码如下所示

class Solution {
public:
    int numIslands(vector>& grid) {
        int row = grid.size();
        int col = grid[0].size();
        int numoflands = 0;
        //从第一行开始遍历,是岛屿则进行周围深度优先搜索
        for(int r = 0;r < row;r++){
            for(int c = 0;c < col;c++){
                if(grid[r][c] == '1'){
                    ++numoflands;
                    dfs(grid,r,c);
                }
            }
        }
        return numoflands;
    }
    //dfs用于消除“1”旁边的“1”并用“0”替换掉防止二次遍历
    void dfs(vector>& grid,int r,int c){
        int nr = grid.size();
        int nc = grid[0].size();
        
        grid[r][c] = '0';//用“0”替换“1”,防止重复调用
        if(r-1>=0&&grid[r-1][c] == '1') dfs(grid,r-1,c);
        if(r+1=0&&grid[r][c-1] == '1') dfs(grid,r,c-1);
        if(c+1

你可能感兴趣的:(Leetcode算法题解,leetcode,笔记,c++)