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
  • 相关阅读:
    [导入]基于Web的B/S结构实时监控系统[转]
    [导入]IE5.0与6.0的区别
    [导入]正确配置和维护Apache WEB Server 安全性
    [导入]又是一个烦人的问题
    [导入]今天就写了这一个语句!
    DNS解析代码copy
    使用uPnP在路由器上映射端口
    查看数据库内存占用
    yield与sleep
    wCF REST
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099824.html
Copyright © 2011-2022 走看看