1+ # 980. Unique Paths III
2+ # On a 2-dimensional grid, there are 4 types of squares:
3+
4+ # 1 represents the starting square. There is exactly one starting square.
5+ # 2 represents the ending square. There is exactly one ending square.
6+ # 0 represents empty squares we can walk over.
7+ # -1 represents obstacles that we cannot walk over.
8+ # Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once.
9+
10+
11+
12+ # Example 1:
13+
14+ # Input: [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
15+ # Output: 2
16+ # Explanation: We have the following two paths:
17+ # 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)
18+ # 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)
19+ # Example 2:
20+
21+ # Input: [[1,0,0,0],[0,0,0,0],[0,0,0,2]]
22+ # Output: 4
23+ # Explanation: We have the following four paths:
24+ # 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)
25+ # 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)
26+ # 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)
27+ # 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)
28+ # Example 3:
29+
30+ # Input: [[0,1],[2,0]]
31+ # Output: 0
32+ # Explanation:
33+ # There is no path that walks over every empty square exactly once.
34+ # Note that the starting and ending square can be anywhere in the grid.
35+
36+
37+ # Note:
38+
39+ # 1 <= grid.length * grid[0].length <= 20
40+
41+ class Solution :
42+ ans = 0
43+ def findPathNum (self , i , j , grid : List [List [int ]], curLen , pLen )-> None :
44+ if (grid [i ][j ]== 2 ):
45+ if (pLen - 1 == curLen ):
46+ self .ans += 1
47+ return
48+ elif (grid [i ][j ]== - 1 ):
49+ return
50+ curLen += 1
51+ grid [i ][j ]= - 1
52+ if (i - 1 >= 0 ):
53+ self .findPathNum (i - 1 , j , grid , curLen , pLen )
54+ if (j - 1 >= 0 ):
55+ self .findPathNum (i , j - 1 , grid , curLen , pLen )
56+ if (i + 1 < len (grid )):
57+ self .findPathNum (i + 1 , j , grid , curLen , pLen )
58+ if (j + 1 < len (grid [0 ])):
59+ self .findPathNum (i , j + 1 , grid , curLen , pLen )
60+ grid [i ][j ]= 0
61+
62+
63+ def uniquePathsIII (self , grid : List [List [int ]]) -> int :
64+ pathLen = 0
65+ start = (0 , 0 )
66+ for i in range (len (grid )):
67+ for j in range (len (grid [0 ])):
68+ if (grid [i ][j ]!= - 1 ):
69+ pathLen += 1
70+ if (grid [i ][j ]== 1 ):
71+ start = (i , j )
72+ self .findPathNum (start [0 ], start [1 ], grid , 0 , pathLen )
73+ return self .ans
74+
0 commit comments