Share my 9ms c++ solution with cleaner


  • 1
    Z

    each time I find a "1" in the grid,

    the result number++,

    and clean every "1" that adjecent.

    and then find another "1"

    and again.

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

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.