[leetcode_medium]Unique Paths II

最近刷题喜欢用github上的leetcode-cli
刷题感觉不错.
使用界面如下:
在这里插入图片描述
也可以看到自己整体的刷题进度:
在这里插入图片描述
第63题是第62题的提升.
题目:
A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).

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.

Note: m and n will be at most 100.

举例:
Example 1:

Input:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:

  1. Right -> Right -> Down -> Down
  2. Down -> Down -> Right -> Right

解析:
就是说如果矩阵中有obstacle,则不能从里面走.
还是用一个和输入矩阵一样大的矩阵记录走的路径个数
每到一个位置,都是左边和上边的和.

res[i][j] = res[i-1][j] + res[i][j-1]    

代码:

  1 class Solution {
  2 public:
  3     int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
  4         int m = obstacleGrid.size(),n = obstacleGrid[0].size();
  5         vector<vector<int>>res(m+1,vector<int>(n+1,0));
  6         res[1][0] = 1;    //保证初始第一步是1即可
  7         for (int i = 1;i <= m;i++)
  8         {
  9             for (int j = 1;j <= n;j++)
 10             {
 11                 if(!obstacleGrid[i-1][j-1])
 12                 {
 13                     res[i][j] = res[i-1][j] + res[i][j-1];
 14                 }
 15             }
 16         }
 17 
 18         return res[m][n];
 19     }
 20 };

猜你喜欢

转载自blog.csdn.net/legalhighhigh/article/details/82820690