Monday, May 12, 2014

LeetCode: Unique Paths II

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


The same idea as Unique Paths. We can just add one more check on the current grid spot if it is an obstacle. If it is, set grid[i][j] to 0.

C++ Code:

/*
 * func: unique_path_with_obstacle
 * goal: to get the total number of paths while obstacles exist
 * @param obstacleGrid: the grid with obstacle in
 * return: total paths
 */
/*
 * The same way as uniquePath, just add one more condition to check if 
 * current spot is an obstacle one
 * complexity: time O(m*n), space O(m*n)
 */
int unique_path_with_obstacle(const vector<vector<int> > &obstacleGrid){
    if(obstacleGrid.size() == 0){
        return 0;
    }
    int m = obstacleGrid.size();
    int n = obstacleGrid[0].size();
    int **grid =  new int* [m];
    for(int i=0; i<m; i++){
        grid[i] = new int[n];
    }
    grid[0][0]=1;
    for(int i=0; i<m; i++){
        for(int j=0; j<n; j++){
            if(i == 0 && j > 0){
                grid[i][j] = grid[i][j-1];
            }else if(i > 0 && j == 0){
                grid[i][j] = grid[i-1][j];
            }else if(i > 0 && j > 0){
                grid[i][j] = grid[i-1][j] + grid[i][j-1];
            }
            if(obstacleGrid[i][j] == 1){
                grid[i][j] = 0;
            }
        }
    }
    int result = grid[m-1][n-1];
    for(int i=0; i<m; i++){
        delete[] grid[i];
    }
    delete [] grid;
    return result;

}

Python Code:

# func: find the number of total unique paths to the target spot while obstacles exist
# @param obstacleGrid: the number of rows
# @return: total numbers
# complexity: time O(m*n), space O(m*n)
def unique_paths(obstacleGrid):
    if not obstacleGrid:
        return 0

    m = len(obstacleGrid)
    n = len(obstacleGrid[0])
    grid = [[1] * n for _ in xrange(m)]
    for i in xrange(m):
        for j in xrange(n):
            if i > 0 and j == 0:
                grid[i][j] = grid[i-1][j]
            elif i == 0 and j > 0:
                grid[i][j] = grid[i][j-1]
            elif i > 0 and j > 0:
                grid[i][j] = grid[i-1][j] + grid[i][j-1]
            if obstacleGrid[i][j] == 1:
                grid[i][j] = 0

    return grid[m-1][n-1]

No comments:

Post a Comment