Saturday, October 5, 2013

63. Unique Paths II ---------M

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?

An obstacle and empty space is marked as 1 and 0 respectively in the grid.

Note: m and n will be at most 100.

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

A:

*************************  第二遍, 1D array *****************************
 Using 1D array to save the status after visiting each row

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int m = obstacleGrid.size();
        int n = obstacleGrid[0].size();
        vector<int> line(n,0);
        line[0] = 1 - obstacleGrid[0][0]; // set 0 if start point is ocupied, otherwise 1
        for(int i =0;i<m;i++){
            for(int j = 0;j<n;j++){
                if(obstacleGrid[i][j]== 1 ){
                    line[j] = 0;
                }else{
                    line[j] += (j==0)?0:line[j-1];
                }
            }
        }
        return line[n-1];
    }
};


Mistakes:
假设的 第一个位置,不能是obctacle的情况,  是不对的

比较tricky的敌方,就是A[1] = 1 - obstacleGrid[0][0];  这里是A[1]是为了设置初始状态

No comments:

Post a Comment