• [Leetcode 58] 63 Unique Path II


    Problem:

    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.

    Analysis:

    Simple DP with some more constraints.

    If a gird is 1, then there's no way to get to this position, the value should be directly set to 0.

    Pay attention to the first inialize of the first row and first column value.

    Code:

     1 class Solution {
     2 public:
     3     int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         int m = obstacleGrid.size();
     7         int n = obstacleGrid[0].size();
     8         int tab[m][n];
     9         
    10         if (obstacleGrid[0][0] == 0)
    11             tab[0][0] = 1;
    12         else
    13             tab[0][0] = 0;
    14         
    15         for (int i=1; i<n; i++) {
    16             if(obstacleGrid[0][i] == 0)
    17                 tab[0][i] = tab[0][i-1];
    18             else
    19                 tab[0][i] = 0;
    20         }
    21         
    22         for (int i=1; i<m; i++) {
    23             if (obstacleGrid[i][0] == 0)
    24                 tab[i][0] = tab[i-1][0];
    25             else
    26                 tab[i][0] = 0;
    27         }
    28         
    29         
    30         for (int i=1; i<m; i++)
    31             for (int j=1; j<n; j++) {
    32                 if (obstacleGrid[i][j] == 0)
    33                     tab[i][j] = tab[i][j-1] + tab[i-1][j];
    34                 else
    35                     tab[i][j] = 0;
    36             }
    37             
    38         return tab[m-1][n-1];
    39         
    40     }
    41 };
    View Code
  • 相关阅读:
    CSP-S 2021游记
    logback-spring.xml配置
    springboot编译的命令
    Springboot 常用注解
    logback如何配置springboot框架
    如何使用IDEA快速创建一个springboot项目
    slf4j、log4j、 logback关系详解和相关用法
    SSM整合及Maven pom.xml
    OO第四单元总结
    OO第三单元总结
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099824.html
Copyright © 2020-2023  润新知