【题解】【矩阵】【回溯】【Leetcode】Unique Paths II

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?

NewImage

Above is a 3 x 7 grid. How many possible unique paths are there?

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.

思路:

很典型的回溯问题,到[i,j]的路径等于到[i-1,j]和[i,j-1]的路径之和,然后为了避免重复求解子问题,结合查表法记录子问题结果。编码要点在于处理 trivial case。

代码:

 1 int uniquePaths2Node(vector<vector<int> > &oGrid, vector<vector<int> > &paths, int i, int j){
 2     //if(i < 0 || j < 0) return 0;//failed [[1]]=>0, 应该把控制条件放下面,不给调用不valid的子问题
 3     if(oGrid[i][j] == 1) return 0;
 4     
 5     if(i == 0 && j == 0) return 1 ^ oGrid[0][0];//failed [[0]]=>1
 6 
 7     int P = 0;
 8     if(i > 0 && oGrid[i-1][j] != 1){
 9         if(paths[i-1][j] == -1)
10             paths[i-1][j] = uniquePaths2Node(oGrid, paths, i-1, j);
11         P += paths[i-1][j];
12     }
13     if(j > 0 && oGrid[i][j-1] != 1){
14         if(paths[i][j-1] == -1)
15             paths[i][j-1] = uniquePaths2Node(oGrid, paths, i, j-1);
16         P += paths[i][j-1];
17     }
18     return P;
19 }
20 int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
21     int m = obstacleGrid.size();
22     if(m == 0) return 0;
23     int n = obstacleGrid[0].size();
24     if(n == 0) return 0;
25 
26     vector<vector<int> > paths(m, vector<int>(n, -1));
27     return uniquePaths2Node(obstacleGrid, paths, m-1, n-1);
28 }
原文地址:https://www.cnblogs.com/wei-li/p/UniquePathsII.html