Suppose there is a robot is located at the top-left corner of a n x m grid (n rows and m columns). The robot can only move either down side or right side at any point in time. The robot wants to reach the bottom-right corner of the grid (marked 'END in the diagram below).
Some cell in the grid is marked, that will be considered as obstacles. So we have to find how many possible unique paths are there? For example if the grid is like [[0,0,0],[0,1,0],[0,0,0]], then the grid will be like below −
Robo | ||
Obs | ||
END |
The output will be 2, So there are total 2 different ways to reach from start position to the end position. These paths are −
Let us see the steps −
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; typedef long long int lli; class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int a = obstacleGrid.size(); int b = obstacleGrid[0].size(); if(!a || !b) return 0; if(obstacleGrid[a - 1][b - 1])return 0; vector < vector <lli> > dp(a, vector <lli>(b)); for(int i = b - 1; i >= 0; i--)if(obstacleGrid[a-1][i]) break; else dp[a-1][i] = 1; for(int i = a - 1; i >= 0; i--)if(obstacleGrid[i][b - 1]) break; else dp[i][b-1] = 1 ; for(int i = a-2; i >= 0; i--){ for(int j = b-2 ; j >= 0; j--)dp[i][j] = !obstacleGrid[i][j]? dp[i+1][j] + dp[i][j+1] : 0; } return dp[0][0]; } }; main(){ Solution ob; vector<vector<int>> v = {{0,0,0},{0,1,0},{0,0,0}}; cout << ob.uniquePathsWithObstacles(v); }
[[0,0,0],[0,1,0],[0,0,0]]
2