sundeepblue
4/12/2014 - 4:04 AM

unique paths I and II, grid

unique paths I and II, grid

/* ==================================================================
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?
Note: m and n will be at most 100.
*/
// a grid of size M*N
int count_number_of_paths(int M, int N) {
    if(M <= 0 || N <= 0) return 0;
    int dp[101][101] = {{0}};
    for(int c=0; c<N; ++c)
        dp[0][c] = 1;
    for(int r=0; r<M; ++r)
        dp[r][0] = 1;
    for(int r=1; r<M; ++r) {
        for(int c=1; c<N; ++c)
            dp[r][c] = dp[r-1][c] + dp[r][c-1];
    }
    return dp[M-1][N-1];
}

/* ==================================================================
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.
Note: m and n will be at most 100.
*/

int count_number_of_paths(vector<vector<int>> &board) {
    if(board.empty()) return 0;
    int M = board.size(), N = board[0].size();
    int dp[101][101] = {{0}};
    for(int c=0; c<N; ++c) {
        if(board[0][c] == 1) break;
        dp[0][c] = 1;
    }
    for(int r=0; r<M; ++r) {
        if(board[r][0] == 1) break;
        dp[r][0] = 1;
    }
    for(int r=1; r<M; ++r) {
        for(int c=1; c<N; ++c) {
            if(board[r][c] == 1) continue; // should be continue not break!
            else dp[r][c] = dp[r-1][c] + dp[r][c-1];
        }
    }
    return dp[M-1][N-1];
}