DFS in C++


  • 0
    L
    class Solution {
    public:
        int numIslands(vector<vector<char> >& grid) {
            if(grid.size()==0)
                return 0;
            int res=0;
            int M = grid.size();
            int N = grid[0].size();
            
            for(int i=0;i<M;i++)
                for(int j=0;j<N;j++)
                   res += numIslands(grid,i,j);
            return res;
        }
    
    private:
        int numIslands(vector<vector<char> >& grid,int i,int j)
        {
            if(grid[i][j]=='1')
            {
                grid[i][j] = '*';
                if(i>0)
                    numIslands(grid,i-1,j);
                if(j>0)
                    numIslands(grid,i,j-1);
                if(i+1<grid.size())
                    numIslands(grid,i+1,j);
                if(j+1<grid[0].size())
                    numIslands(grid,i,j+1);
                return 1;
            }
                return 0;
        }
    };
    

Log in to reply
 

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