63. Unique Paths II(中等, 能独立做出来的DP类第二个题^^)

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 are 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.

这是自己能独立做出来的DP类第二个题^^.
这题和上一题状体转移公式几乎一样.区别就是在 obstacles 的处理上.下面是方法:
核心思路:

  1. 先搞定第 0 行和第 0 列;
  2. 第 0 行和第 0 列若有障碍, 则该处及后面的都 = 0;
  3. 非0行、列,则按公式填写 bp matrix, 从 row=1, col=1开始. 若遇 obstacle, 该处设置为0.

注意处理 special caseif(A[0][0] = 1) return 0;
为了搞起来方便,申请了一个 m*n 的二维数组.但似乎只申请 n 维的一维数组就足够了.先不管啦.

自己思路,自个媳妇:
(O(m*n)) time, (O(m*n)) extra space.

// 思路:
// 1. 先搞定第 0 行和第 0 列;
// 2. 第 0 行和第 0 列若有障碍, 则该处及后面的都 = 0;
// 3. 非0行、列,则按公式填写 bp matrix, 从 row=1, col=1开始.
//    若遇 obstacle, 该处设置为0.
int uniquePathsWithObstacles(vector<vector<int>>& A) {
	const int m = A.size(), n = A[0].size();
	// special case
	if (m == 0 || A[0][0] == 1)
		return 0;

	vector<vector<int>> dp(m);

	// dp[m*n] initializaion
	for (int i = 0; i < m; i++)
		dp[i].resize(n);

	// 初始化bp的行
	for (int j = 0; j < n; j++) {
		if (A[0][j] == 0)
			dp[0][j] = 1;
		else { // point A[0,j] is an obstacle
			dp[0][j] = 0;
			break; // 第0行若有障碍,则该处及后面的都 = 0
		}
	}

	// 初始化bp的列
	for (int i = 1; i < m; i++) {
		if (A[i][0] == 0)
			dp[i][0] = 1;
		else { // point A[i,0] is an obstacle
			dp[i][0] = 0;
			break; // 第0列若有障碍,则该处及后面的都 = 0
		}
	}

	// 按公式填写bp matrix, 从 row=1, col=1开始
	for (int i = 1; i < m; i++) {
		for (int j = 1; j < n; j++) {
			if (A[i][j] == 1)
				dp[i][j] == 0; //障碍处设置为0
			// dp的状态转移公式
			else if (A[i][j] == 0)
				dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
		}
	}
	return dp[m - 1][n - 1];
}
原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7462307.html