sourcecode

Tuesday, January 1, 2013

Unique Paths ( I and II )


Unique Paths
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?
Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
class Solution {
public:
    int uniquePaths(int m, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int a[m+1][n+1];
        if (!m || !n) return 1;
        for(int ii = 0; ii <= n; ++ii){
            a[0][ii] = 0;
        }
        for(int ii = 0; ii <= m; ++ii){
            a[ii][0] = 0;
        }
        a[0][1] = 1;
        for(int row = 1; row <= m; ++row){
            for(int col = 1; col <= n; ++col){
                a[row][col] = a[row-1][col] + a[row][col-1];
            }
        }
        return a[m][n];
    }
};

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.

class Solution {//almost identical to the previous one. Just mark the grid of
//an obstacle to zero
public:
    int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int const m = obstacleGrid.size();
        if (!m) return 1;
        int const n = obstacleGrid[0].size();
        
        int a[m+1][n+1];
        if (!m || !n) return 1;
        for(int ii = 0; ii <= n; ++ii){
            a[0][ii] = 0;
        }
        for(int ii = 0; ii <= m; ++ii){
            a[ii][0] = 0;
        }
        a[0][1] = 1;
        for(int row = 1; row <= m; ++row){
            for(int col = 1; col <= n; ++col){
                a[row][col] = (obstacleGrid[row-1][col-1]?0:a[row-1][col] + a[row][col-1]);
            }
        }
        return a[m][n];
    }
};

No comments: