- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 76 lines of Python from the credited upstream file 1728.py.
- The implementation visibly relies on sequence storage, cached states.
- No explicit loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def canMouseWin(self, grid: list[str], catJump: int, mouseJump: int) -> bool:3 DIRS = ((0, 1), (1, 0), (0, -1), (-1, 0))4 m = len(grid)5 n = len(grid[0])6 nFloors = 07 cat = 0 8 mouse = 0 9 10 def hash(i: int, j: int) -> int:11 return i * n + j12 13 for i in range(m):14 for j in range(n):15 if grid[i][j] != '#':16 nFloors += 117 if grid[i][j] == 'C':18 cat = hash(i, j)19 elif grid[i][j] == 'M':20 mouse = hash(i, j)21 22 @functools.lru_cache(None)23 def dp(cat: int, mouse: int, turn: int) -> bool:24 """25 Returns True if the mouse can win, where the cat is on (i / 8, i % 8), the26 mouse is on (j / 8, j % 8), and the turns is k.27 """28 29 if turn == nFloors * 2:30 return False31 32 if turn % 2 == 0:33 34 i = mouse n35 j = mouse % n36 for dx, dy in DIRS:37 for jump in range(mouseJump + 1):38 x = i + dx * jump39 y = j + dy * jump40 if x < 0 or x == m or y < 0 or y == n:41 break42 if grid[x][y] == '#':43 break44 45 if grid[x][y] == 'F':46 return True47 if dp(cat, hash(x, y), turn + 1):48 return True49 50 return False51 else:52 53 i = cat n54 j = cat % n55 for dx, dy in DIRS:56 for jump in range(catJump + 1):57 x = i + dx * jump58 y = j + dy * jump59 if x < 0 or x == m or y < 0 or y == n:60 break61 if grid[x][y] == '#':62 break63 64 if grid[x][y] == 'F':65 return False66 nextCat = hash(x, y)67 68 if nextCat == mouse:69 return False70 if not dp(nextCat, mouse, turn + 1):71 return False72 73 return True74 75 return dp(cat, mouse, 0)76