跳到主要内容

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 3 × 3 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.

备忘录法

在上一题的基础上改一下即可。相比动规,简单得多。

# Unique Paths II
# DFS + caching, aka memoization
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: list[list[int]]) -> int:
m = len(obstacleGrid)
n = len(obstacleGrid[0])
if obstacleGrid[0][0] != 0 or obstacleGrid[m-1][n-1] != 0:
return 0

self.f = [[0] * n for _ in range(m)]
self.f[0][0] = 0 if obstacleGrid[0][0] != 0 else 1
return self.dfs(obstacleGrid, m-1, n-1)

# @return total number of paths from (0,0) to (x,y)
def dfs(self, obstacleGrid: list[list[int]], x: int, y: int) -> int:
if x < 0 or y < 0: # invalid data, termination condition
return 0

# (x,y) is obstacle
if obstacleGrid[x][y] != 0:
return 0

if x == 0 and y == 0: # back to start point, convergence condition
return self.f[0][0]

if self.f[x][y] > 0:
return self.f[x][y]
else:
self.f[x][y] = self.dfs(obstacleGrid, x-1, y) + self.dfs(obstacleGrid, x, y-1)
return self.f[x][y]

动规

与上一题类似,但要特别注意第一列的障碍。在上一题中,第一列全部是 1,但是在这一题中不同,第一列如果某一行有障碍物,那么后面的行全为 0。

// Unique Paths II
// 动规,滚动数组
// 时间复杂度 O(n^2),空间复杂度 O(n)
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
final int m = obstacleGrid.length;
final int n = obstacleGrid[0].length;
if (obstacleGrid[0][0] != 0 ||
obstacleGrid[m-1][n-1] != 0) return 0;

int[] f = new int[n];
f[0] = obstacleGrid[0][0] != 0 ? 0 : 1;

for (int i = 0; i < m; i++) {
f[0] = f[0] == 0 ? 0 : (obstacleGrid[i][0] != 0 ? 0 : 1);
for (int j = 1; j < n; j++)
f[j] = obstacleGrid[i][j] != 0 ? 0 : (f[j] + f[j - 1]);
}

return f[n - 1];
}

}

相关题目