zoukankan      html  css  js  c++  java
  • [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
  • 相关阅读:
    频率组件
    Django-admin组件
    Python全栈开发课堂笔记_day03
    python全栈开发day02
    python全栈开发day01
    正确认知自己,做真实的自己
    翻出大学时期收集的文章来看看
    mybatis中的#{}和${}
    Parameter index out of range (2 > number of parameters, which is 1)
    中间件
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099824.html
Copyright © 2011-2022 走看看