zoukankan      html  css  js  c++  java
  • Unique Paths II [LeetCode]

    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.

    Solution: The same to Unique Paths, just add obstacle check.

     1 class Solution {
     2 public:
     3     int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
     4         if(obstacleGrid.size() <= 0 || obstacleGrid[0].size() <= 0)
     5             return 0;
     6 
     7         int row = obstacleGrid.size();
     8         int column = obstacleGrid[0].size();
     9         vector<int> path_nums(column, 0);
    10         for(int i = 0; i < row; i ++) {
    11             int row_idx = row - 1 - i;
    12             for(int j = 0; j < column; j ++ ) {
    13                 int column_idx = column - 1 - j;
    14                 if(i == 0 && j == 0 && obstacleGrid[row_idx][column_idx] == 1)
    15                     return 0;
    16                 if(i == 0 && j == 0 && obstacleGrid[row_idx][column_idx] == 0) {
    17                     path_nums[j] = 1;
    18                 }else {
    19                     if(obstacleGrid[row_idx][column_idx] == 1) {
    20                         path_nums[j] = 0;
    21                     }else {
    22                         if(j != 0)
    23                             path_nums[j] += path_nums[j - 1];
    24                     }
    25                 }
    26             } 
    27         }
    28         return path_nums[column - 1];
    29     }
    30 };
  • 相关阅读:
    62-函数的调用
    40-字符串类型内置方法
    47-Python进阶小结
    44-集合的内置方法
    45-数据类型分类
    43-字典类型内置方法
    42-元组类型内置方法
    41-列表类型内置方法
    es6 Reflect对象详解
    微信小程序之公共组件写法
  • 原文地址:https://www.cnblogs.com/guyufei/p/3403586.html
Copyright © 2011-2022 走看看