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
  • 相关阅读:
    面向对象案例
    0429面向对象3.0
    Linux系统常用命令以及常见问题的解决方法
    VS2010查看源码对应的汇编语言
    【学习笔记】python
    Linux环境配置错误记录
    【学习笔记】TensorFlow
    git基本操作
    位操作的个人总结
    Java字符串拼接
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099824.html
Copyright © 2011-2022 走看看