63.Unique Paths II
Follow up for "Unique Paths":
Now consider if some obstacles are added tothe grids. How many unique paths would there be?
An obstacle and empty space is marked as 1and 0 respectively in the grid.
For example,
There is one obstacle in the middle of a3x3 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
算法思想
利用动态规划的思想进行填表,找出状态转移方程,a[i][j] = a[i-1][j] + a[i][j-1]。这个方程是根据在第i行第j列,有两种方式可以到达,第一种方式就是从a[i-1][j]这个格子过去,还有一个格子就是a[i][j-1]这个格子过去。需要注意的是,第一行和第一列的初始化问题。填表是根据第一行,第一列来填的,所以要注意边界问题。
步骤
1. 申请一个新的矩阵。并初始化第一行,第一列,若原矩阵第一行,第一列存在1,则该下标后面对于的行或者列元素全部赋值为0。
2. 遍历原矩阵,在新矩阵进行填表,若上一个位置不为1,则当前位置等于上个位置的路径和。a[i][j]+=a[i-1][j],a[i][j]+=a[i][j-1]。
3. 最后返回a[i-1][j-1]。
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& v) {
if(v.size() < 1)return 0;
int n = v.size();//Row
int m = v[0].size();//Column
int r,l;
int** a = new int*[n];
for(int i = 0 ; i < n ; i++)a[i] = new int[m];
for(int i = 0 ; i < n ; i++)
for(int j = 0 ; j < m ; j++)
a[i][j] = 0;
int value = 1;
for(int i = 0 ; i < m ; i++){
if(v[0][i])value = 0;
a[0][i] = value;
}
value = 1;
for(int i = 0 ; i < n ; i++){
if(v[i][0])value = 0;
a[i][0] = value;
}
for(int i = 1; i < n ; i++){
for(int j = 1 ; j < m ; j++){
if(v[i][j])continue;
if(!v[i-1][j])a[i][j]+=a[i-1][j];
if(!v[i][j-1])a[i][j]+=a[i][j-1];
// cout << a[i][j] << " - ";
}//for j
cout << endl;
}//for i
n-1 > 0 ? r = n-1 : r = 0;
m-1 > 0 ? l = m-1 : l = 0;
//cout << "r - >" << r << " l ->"<< l << endl;
return a[r][l];
}
};