# 【LeetCode】 63. Unique Paths II ## Description > 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). > Now consider if some obstacles are added to the grids. How many unique paths would there be? > 有一個機器人在一個m*n的網格裡的最左上角。 > 它每次只能往下或往右走一格,它的終點是最右下角。 > 現在需要考慮在網格上可能有障礙物,它有幾種不同的路徑? ![](https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png) > An obstacle and empty space is marked as 1 and 0 respectively in the grid. > Note: m and n will be at most 100. > 障礙物和空格在網格上分別用1和0表示。 > 提示:m和n最多只有100。 ## Example: ``` Example 1: Input: [ [0,0,0], [0,1,0], [0,0,0] ] Output: 2 Explanation: There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right ``` ## Solution * 使用DP解,`自己這格的路徑` = `上面那格的路徑` + `左邊那格的路徑` * 再設定特殊狀況:障礙物路徑數必定為`0`、超出邊界路徑數=`0`、起始點=`0`。 ### Code ```C++=1 class Solution { public: int getPath(vector<vector<int>>& obstacleGrid, int *table[], int x, int y) { //out of board if(x<0||y<0) return 0; //have obstacle if(obstacleGrid[y][x]==1) return 0; //start point if(x==0&&y==0) return 1; //recursion get answer if(table[y][x] == -1) table[y][x] = getPath(obstacleGrid,table,x-1,y) + getPath(obstacleGrid,table,x,y-1); return table[y][x]; } int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { //get size of grid. int s_y = obstacleGrid.size(); int s_x = obstacleGrid[0].size(); //make DP table int **table = new int*[s_y]; for(int i=0;i<s_y;i++) table[i] = new int[s_x]; for(int i=0;i<s_y;i++) for(int j=0;j<s_x;j++) table[i][j] = -1; return getPath(obstacleGrid,table,s_x-1,s_y-1); } }; ``` ###### tags: `LeetCode` `C++`