题意:给出一个01矩阵,1表示所在格子不能通过,求从0,0走到n,m的不同方案数。
题解:DP,dp[i][j]表示从0,0走到i,j的方案数。转移:dp[i][j] = dp[i - 1][j] + dp[i][j - 1],在左边和上边的格子都为1的情况下。不然就哪里为0从哪里转移。注意初始化。
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int n = obstacleGrid.size();
if(n == 0) return 0;
int m = obstacleGrid[0].size();
int dp[n][m];
memset(dp,0,sizeof(dp));
bool flag = false;
for(int i = 0; i < m; i++)
{
if(obstacleGrid[0][i])
flag = true;
if(!flag)
dp[0][i] = 1;
}
flag = false;
for(int i = 0; i < n; i++)
{
if(obstacleGrid[i][0])
flag = true;
if(!flag)
dp[i][0] = 1;
}
for(int i = 1; i < n; i++)
{
for(int j = 1; j < m; j++)
{
if(!obstacleGrid[i][j])
{
int a = 0, b = 0;
if(!obstacleGrid[i - 1][j]) a = dp[i - 1][j];
if(!obstacleGrid[i][j - 1]) b = dp[i][j - 1];
dp[i][j] = a + b;
}
}
}
return dp[n - 1][m - 1];
}
};