zoukankan      html  css  js  c++  java
  • 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.
    Note: m and n will be at most 100.

    Solution: Dynamic programming.

     1 class Solution {
     2 public:
     3     int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
     4         int res = 0;
     5         int M = obstacleGrid.size();
     6         int N = obstacleGrid[0].size();
     7         int dp[M][N];
     8         dp[0][0] = obstacleGrid[0][0] == 1 ? 0 : 1;
     9         
    10         for(int i = 1; i < M; i++) {
    11             dp[i][0] = obstacleGrid[i][0] == 1 ? 0 : dp[i-1][0];
    12         }
    13         for(int j = 1; j < N; j++) {
    14             dp[0][j] = obstacleGrid[0][j] == 1 ? 0 : dp[0][j-1];
    15         }
    16         for(int i = 1; i < M; i++) {
    17             for(int j = 1; j < N; j++) {
    18                 if(obstacleGrid[i][j] == 1) dp[i][j] = 0;
    19                 else {
    20                     dp[i][j] = dp[i-1][j] + dp[i][j-1];
    21                 }
    22             }
    23         }
    24         return dp[M-1][N-1];
    25     }
    26 };
  • 相关阅读:
    从1到n中找到任意num个数的和为sum的所有组合
    算法导论5.12
    使用c++技术实现下载网页
    算法导论5.13
    感慨
    算法导论2.37
    [转载]Yahoo!的分布式数据平台PNUTS简介及感悟
    Bigtable 论文笔记
    GFS 论文笔记
    MapReduce论文笔记
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3655570.html
Copyright © 2011-2022 走看看