Unique Paths II
Total Accepted: 22828 Total Submissions: 81414My SubmissionsFollow up for "Unique Paths":
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.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[ [0,0,0], [0,1,0], [0,0,0] ]
The total number of unique paths is 2
.
Note: m and n will be at most 100.
把存在Obstacle的位置标记为-1,表示无法通行
1 class Solution { 2 public: 3 int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { 4 int m=obstacleGrid.size(); 5 int n=obstacleGrid[0].size(); 6 7 int dp[101][101]; 8 9 dp[0][0]=obstacleGrid[0][0]==1?-1:1; 10 11 for(int i=1;i<m;i++) 12 { 13 if(obstacleGrid[i][0]==1) 14 { 15 dp[i][0]=-1; 16 continue; 17 } 18 if(dp[i-1][0]==-1) dp[i][0]=-1; 19 else dp[i][0]=1; 20 } 21 22 for(int j=1;j<n;j++) 23 { 24 if(obstacleGrid[0][j]==1) 25 { 26 dp[0][j]=-1; 27 continue; 28 } 29 30 if(dp[0][j-1]==-1) dp[0][j]=-1; 31 else dp[0][j]=1; 32 } 33 34 for(int i=1;i<m;i++) 35 { 36 for(int j=1;j<n;j++) 37 { 38 if(obstacleGrid[i][j]==1) 39 { 40 dp[i][j]=-1; 41 continue; 42 } 43 if(dp[i-1][j]==-1&&dp[i][j-1]==-1) dp[i][j]=-1; 44 else if(dp[i-1][j]==-1&&dp[i][j-1]!=-1) dp[i][j]=dp[i][j-1]; 45 else if(dp[i-1][j]!=-1&&dp[i][j-1]==-1) dp[i][j]=dp[i-1][j]; 46 else if(dp[i-1][j]!=-1&&dp[i][j-1]!=-1) dp[i][j]=dp[i-1][j]+dp[i][j-1]; 47 } 48 } 49 50 return dp[m-1][n-1]==-1?0:dp[m-1][n-1]; 51 } 52 };
实际上不用标记也可以,dp[i][j]=0就表示了没有路
1 class Solution { 2 public: 3 int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { 4 int m=obstacleGrid.size(); 5 int n=obstacleGrid[0].size(); 6 7 int dp[101][101]; 8 //vector<vector<int>> dp(m,vector<int>(n)); 9 10 dp[0][0]=obstacleGrid[0][0]==1?0:1; 11 for(int i=1;i<m;i++) 12 { 13 dp[i][0]=obstacleGrid[i][0]==1?0:dp[i-1][0]; 14 } 15 for(int j=1;j<n;j++) 16 { 17 dp[0][j]=obstacleGrid[0][j]==1?0:dp[0][j-1]; 18 } 19 for(int i=1;i<m;i++) 20 { 21 for(int j=1;j<n;j++) 22 { 23 dp[i][j]=obstacleGrid[i][j]==1?0:dp[i-1][j]+dp[i][j-1]; 24 } 25 } 26 27 return dp[m-1][n-1]; 28 } 29 };