zoukankan      html  css  js  c++  java
  • 63. 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.

     1 class Solution {
     2 public:
     3     int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
     4         if(obstacleGrid.empty() || obstacleGrid[0].empty()){
     5             return 0;
     6         }
     7         int row = obstacleGrid.size();
     8         int col = obstacleGrid[0].size();
     9         
    10         int dp[row][col];
    11         
    12         dp[0][0] = (obstacleGrid[0][0] == 0 ? 1 : 0);
    13         
    14         for(int i = 1; i < row; i++){
    15             dp[i][0] = ((dp[i-1][0] == 1 && obstacleGrid[i][0] == 0)? 1 : 0);
    16         }
    17         
    18         for(int j = 1; j < col; j++){
    19             dp[0][j] = ((dp[0][j-1] == 1 && obstacleGrid[0][j] == 0)? 1: 0);
    20         }
    21         
    22         for(int i = 1 ; i < row; i++){
    23             for(int j = 1 ; j < col;j++){
    24                 if(obstacleGrid[i][j] == 1){
    25                     dp[i][j] = 0;
    26                 }else{
    27                     dp[i][j] = dp[i-1][j]+dp[i][j-1];
    28                 }
    29             }
    30         }
    31         
    32         return dp[row-1][col-1];
    33     }
    34 };
  • 相关阅读:
    JAVA---JDK环境变量的配置
    “==” 与“equals(Object)”区别
    js替换字符串中所有斜杠
    uploadify学习笔记
    VBA学习笔记
    浮动导航条的实现
    canvas初识笔记
    EntityFramework存储过程的返回类型
    CSS及html的特殊字符表
    DIV六种实现元素水平居中
  • 原文地址:https://www.cnblogs.com/sankexin/p/5871282.html
Copyright © 2011-2022 走看看