c_cpp 独特的路径I和II,网格

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 独特的路径I和II,网格相关的知识,希望对你有一定的参考价值。

/* ==================================================================
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];
}



以上是关于c_cpp 独特的路径I和II,网格的主要内容,如果未能解决你的问题,请参考以下文章

63. 不同路径 II

63-不同路径 II

LeetCode 63. 不同路径 II(Unique Paths II)

63. 不同路径 II

[LeetCode] 63. 不同路径 II

63. 不同路径 II