[LeetCode] 63. Unique Paths II

来源:互联网 发布:c语言三角形判断 编辑:程序博客网 时间:2024/06/06 08:48

题目链接: https://leetcode.com/problems/unique-paths-ii/

Description

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.

解题思路

和上一题 62. Unique Paths,基本思路是一样的,只不过多了一些不能走的障碍,遇到就把 maps[j] 赋值 0 就好了。

Code

class Solution {public:    int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {        int m = obstacleGrid.size();        if (m == 0) return 0;        int n = obstacleGrid[0].size();        if (n == 0) return 0;        if (obstacleGrid[0][0] == 1 || obstacleGrid[m - 1][n - 1] == 1) return 0;        vector<int> maps(n);        maps[0] = 1;        for (int i = 0; i < m; ++i) {            for (int j = 0; j < n; ++j) {                if (obstacleGrid[i][j] == 1) maps[j] = 0;                else maps[j] += maps[j - 1];            }        }        return maps[n - 1];    }};
0 0
原创粉丝点击