leetcode Unique Paths II

原创 2013年12月03日 21:03:10

Unique Paths II

 Total Accepted: 2092 Total Submissions: 8049My Submissions

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.


I actually submitted the code with TLE using DFS. DP is the right solution:

class Solution {
 public:
  int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) {
    int m = obstacleGrid.size(), n = m == 0 ? 0 : obstacleGrid[0].size(), count = 0;
    if (m == 0 || n == 0)
      return count;
    vector<vector<int>> dp(m, vector<int>(n, 0));
    int i, j;
    if (obstacleGrid[0][0] == 1)
      return 0;
    else
      dp[0][0] = 1;
    for (j = 1; j < n; ++j)
      dp[0][j] = dp[0][j - 1] & (obstacleGrid[0][j] == 0);
    for (i = 1; i < m; ++i)
      dp[i][0] = dp[i - 1][0] & (obstacleGrid[i][0] == 0);
    
    for (i = 1; i < m; ++i)
      for (j = 1; j < n; ++j)
        if (obstacleGrid[i][j] == 0)
          dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
        else
          dp[i][j] = 0;
    return dp[m - 1][n - 1];

  }
};


LeetCode - 63. Unique Paths II

这道题目与上一个题目是一样的,只是在matrix中有些小格子里有障碍,无法通行。基本的思路与上道题目是一样的,只是在初始化和进行DP的时候都要先进行一下检查,检查当前的访问到的[i][j] == 1,...

【leetcode】Unique Paths II

题目:与版本一不同的是,这里给定了一个矩阵,矩阵中元素为0的点表示该点可达,为1的点表示不可达,当然,不可达也就意味着不可经过。以左上角为出发点,右下角为目标终点,可行的不同路径有多少。 分析: 在U...

Unique Paths II-leetcode

这道题是Uniue Paths的一个变种,却然我受益匪浅。 由于第一道题目我使用排列组合的算法做的,导致这道题目用同样的办法就会很麻烦。 使用第一问的结论来进行求解,将每个障碍划分为障碍之上和障碍...

leetcode - 62,63. Unique Paths(II) & 64.Minimum Path Sum

算法系列博客之Dynamic Programming 本篇博客将运用动态规划的思想来解决leetcode上264号问题这三个题目的共同之处在于均是二维矩阵上的规划问题问题描述:62 Unique Pa...
  • Quiteen
  • Quiteen
  • 2017年06月11日 20:40
  • 126

leetcode: Unique Paths II

TLE 递归tai'ma
  • hkx1030
  • hkx1030
  • 2014年06月26日 21:26
  • 290

Unique Paths II leetcode

Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How many uniqu...

LeetCode Solutions : Unique Paths I & II

Unique Paths  A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagr...
  • lviiii
  • lviiii
  • 2014年09月11日 17:30
  • 726

LeetCode63——Unique Paths II

LeetCode63——Unique Paths II 跟LeetCode62——Unique Paths不同的是,这里是要在路径上设置障碍的。 因此不能用组合的方法去做了(也许可以,但我实在想不到)...

LeetCode_63---Unique Paths II

Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How many unique...

LeetCode | Unique Paths I,II

A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below). ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode Unique Paths II
举报原因:
原因补充:

(最多只允许输入30个字)