Simple solution C++, using DP and BFS both


#1

using DP solution



    int Solution::uniquePathsWithObstacles(vector<vector<int> > &grid) {
        int r = grid.size();
        int c = grid[0].size();
        
        vector<vector<int>>dp(r,vector<int>(c));
        
        for(int i=0;i<r;i++){
            if(grid[i][0]==0)
                dp[i][0]=1;
            else
                break;
        }
        
        for(int i=0;i<c;i++){
            if(grid[0][i]==0)
                dp[0][i]=1;
            else
                break;
        }
        
        for(int i=1;i<r;i++){
            for(int j=1;j<c;j++){
                if(grid[i][j]==1)
                    continue;
                else
                    dp[i][j] = dp[i-1][j]+dp[i][j-1];
            }
        }
        return dp[r-1][c-1];
    }

Method 2: using BFS traversal



    int Solution::uniquePathsWithObstacles(vector<vector<int> > &a) {
        int r=a.size();
        int c = a[0].size();
        if(a[0][0]==1) return 0;
        queue<pair<int,int>>q;
        q.push(make_pair(0,0));
        
        int count=0;
        while(!q.empty()){
            pair<int,int>p = q.front();
            q.pop();
            
            if(p.first == r-1 && p.second == c-1)
                count++;
                
            if(p.first+1<r && a[p.first+1][p.second] == 0)
                q.push(make_pair(p.first+1,p.second));
                
            if(p.second<c && a[p.first][p.second+1] == 0)
                q.push(make_pair(p.first,p.second+1));
        }
        return count;
    }