Skip to content

Instantly share code, notes, and snippets.

@pdu
Created February 16, 2013 12:00
Show Gist options
  • Select an option

  • Save pdu/4966606 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4966606 to your computer and use it in GitHub Desktop.
Follow 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 i…
#define MAXN 100
int ans[MAXN][MAXN];
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
int n = obstacleGrid.size();
int m = obstacleGrid[0].size();
for (int i = 0; i < n; ++i)
for (int j = 0; j < m; ++j) {
ans[i][j] = 0;
if (obstacleGrid[i][j] == 1)
continue;
if (i == 0 && j == 0)
ans[i][j] = 1;
if (i - 1 >= 0)
ans[i][j] += ans[i - 1][j];
if (j - 1 >= 0)
ans[i][j] += ans[i][j - 1];
}
return ans[n - 1][m - 1];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment