LeetCode Algorithm 0063 - Unique Paths II (Medium)
Problem Link: https://leetcode.com/problems/unique-paths-ii/
Related Topics: Array
Dynamic Programming
Description
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).
How many possible unique paths are there?
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
Solution C++
// Author: https://blog.csdn.net/DarkRabbit
// Problem: https://leetcode.com/problems/unique-paths-ii/
// Difficulty: Medium
// Related Topics: `Array` `Dynamic Programming`
#pragma once
#include "pch.h"
namespace P63UniquePathsII
{
class Solution
{
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid)
{
int rows = obstacleGrid.size();
if (rows == 0)
{
return 0;
}
int cols = obstacleGrid[0].size();
if (cols == 0)
{
return 0;
}
if (obstacleGrid[0][0] == 1)
{
return 0;
}
// 初始化全0走法二维数组(路径数量)
vector<vector<long long>> pathCount = vector<vector<long long>>(rows, vector<long long >(cols, 0));
pathCount[0][0] = 1LL;
// 第一列的行,都只有1种走法
for (int r = 1; r < rows; r++)
{
if (obstacleGrid[r][0] == 1)
{
break;
}
else
{
pathCount[r][0] = 1;
}
}
// 第一行的列,都只有1种走法
for (int c = 1; c < cols; c++)
{
if (obstacleGrid[0][c] == 1)
{
break;
}
else
{
pathCount[0][c] = 1;
}
}
// 中间网格,每个网格都可以由 “上”“左” 两个方向来,
// 则走到这个网格的数量是,两个方向走法的和
for (int r = 1; r < rows; r++)
{
for (int c = 1; c < cols; c++)
{
if (obstacleGrid[r][c] != 1)
{
pathCount[r][c] = pathCount[r - 1][c] + pathCount[r][c - 1];
}
}
}
return pathCount[rows - 1][cols - 1];
}
};
}