当前位置:编程学习 > C/C++ >>

[leetcode]Unique Paths II

class Solution {
public:
    int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(obstacleGrid.empty()) return 0;
        int m = obstacleGrid.size();
        int n = obstacleGrid[0].size();
        
        vector<vector<int>> f(m, vector<int>(n, 0));
        
        for(int j = 0; j < n; j++){
            if(obstacleGrid[0][j] == 1){
                break;
            }else{
                f[0][j] = 1;
            }
        }
        
        for(int i = 0; i < m; i++){
            if(obstacleGrid[i][0] == 1){
                break;
            }else{
                f[i][0] = 1;
            }
        }
        
        for(int i = 1; i < m; i++){
            for(int j = 1; j < n; j++){
                if(obstacleGrid[i][j] == 1){
                    f[i][j] = 0;
                }else{
                    f[i][j] = f[i-1][j] + f[i][j-1];
                }  
            }
        }
        return f[m-1][n-1];
    }
};

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,