Unique Paths II(cp,cpp,dp)

 Unique Paths II(cp,cpp,dp)

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

Now consider if some obstacles are added to the grids. How many unique paths would there be?

  

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& a)
    {
        int n=a.size();
        int m=a[0].size();
       
        int t[n][m];
        memset(t,0,sizeof(t));
        for(int i=0;i<m;i++)
        {
            if(a[0][i]==0)
               t[0][i]=1;
            else
                break;
           
        }
         for(int i=0;i<n;i++)
        {
            if(a[i][0]==0)
               t[i][0]=1;
            else
                break;
           
        }
         for(int i=1;i<n;i++)
        {
            for(int j=1;j<m;j++)
            {
                if(a[i][j]!=1 )
                     t[i][j]=t[i-1][j]+t[i][j-1];
                else
                     t[i][j]=0;
            }
         }
        return t[n-1][m-1];
       
    }
};

Comments

Popular posts from this blog

inorder traversal without using recursion

Amazing Subarrays(cpp,interviewbit)

Preorder Traversal without recursion