Skip to content

Commit 2c8ff62

Browse files
committed
solve Unique Paths III
1 parent c369b42 commit 2c8ff62

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

problems/unique_paths_iii.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
# We have the following grid:
6+
# 1, 0, 0, 0
7+
# 0, 0, 0, 0
8+
# 0, 0, 2, -1
9+
# Walk over every non-obstacle square exactly once.
10+
#
11+
# 1, 0, 0, 0
12+
# 0, 0, 0, 0
13+
# 0, 0, 0, 2
14+
#
15+
# Straight Forward DFS.
16+
# Time: O(4 ^ (r * c)), exponential time.
17+
# Space: O(r * c)
18+
# where r and c are the number of rows or columns.
19+
#
20+
# Since r * c <= 20, this solution is accepted.
21+
def uniquePathsIII(self, grid: List[List[int]]) -> int:
22+
rows, cols, paths, visited, num_valid_squares, start_i, start_j = (
23+
len(grid),
24+
len(grid[0]),
25+
0,
26+
set(),
27+
0,
28+
None,
29+
None,
30+
)
31+
32+
for i in range(rows):
33+
for j in range(cols):
34+
if grid[i][j] in (0, 1):
35+
num_valid_squares += 1
36+
if grid[i][j] == 1:
37+
start_i, start_j = i, j
38+
39+
def dfs(i, j):
40+
if grid[i][j] == 2:
41+
if len(visited) == num_valid_squares:
42+
nonlocal paths
43+
paths += 1
44+
45+
return
46+
47+
visited.add((i, j))
48+
49+
for dir in ((1, 0), (0, -1), (-1, 0), (0, 1)):
50+
nbr_i, nbr_j = i + dir[0], j + dir[1]
51+
if (
52+
0 <= nbr_i < rows
53+
and 0 <= nbr_j < cols
54+
and grid[nbr_i][nbr_j] != -1
55+
and (nbr_i, nbr_j) not in visited
56+
):
57+
dfs(i=nbr_i, j=nbr_j)
58+
59+
visited.remove((i, j))
60+
61+
dfs(i=start_i, j=start_j)
62+
63+
return paths

tests/test_unique_paths_iii.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import unittest
2+
3+
from unique_paths_iii import Solution
4+
5+
6+
class TestUniquePathsIII(unittest.TestCase):
7+
def test_example_1(self):
8+
grid = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 2, -1]]
9+
assert Solution().uniquePathsIII(grid=grid) == 2
10+
11+
def test_example_2(self):
12+
grid = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 2]]
13+
assert Solution().uniquePathsIII(grid=grid) == 4
14+
15+
def test_example_3(self):
16+
grid = [[0, 1], [2, 0]]
17+
assert Solution().uniquePathsIII(grid=grid) == 0

0 commit comments

Comments
 (0)