Cat and Mouse II Problem
Description
LeetCode Problem 1728.
A game is played by a cat and a mouse named Cat and Mouse.
The environment is represented by a grid of size rows x cols, where each element is a wall, floor, player (Cat, Mouse), or food.
- Players are represented by the characters
'C'(Cat),'M'(Mouse). - Floors are represented by the character
'.'and can be walked on. - Walls are represented by the character
'#'and cannot be walked on. - Food is represented by the character
'F'and can be walked on. - There is only one of each character
'C','M', and'F'ingrid.
Mouse and Cat play according to the following rules:
- Mouse moves first, then they take turns to move.
- During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the
grid. catJump, mouseJumpare the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length.- Staying in the same position is allowed.
- Mouse can jump over Cat.
The game can end in 4 ways:
- If Cat occupies the same position as Mouse, Cat wins.
- If Cat reaches the food first, Cat wins.
- If Mouse reaches the food first, Mouse wins.
- If Mouse cannot get to the food within 1000 turns, Cat wins.
Given a rows x cols matrix grid and two integers catJump and mouseJump, return true if Mouse can win the game if both Cat and Mouse play optimally, otherwise return false.
Example 1:

Input: grid = ["####F","#C...","M...."], catJump = 1, mouseJump = 2
Output: true
Explanation: Cat cannot catch Mouse on its turn nor can it get the food before Mouse.
Example 2:

Input: grid = ["M.C...F"], catJump = 1, mouseJump = 4
Output: true
Example 3:
Input: grid = ["M.C...F"], catJump = 1, mouseJump = 3
Output: false
Constraints:
rows == grid.lengthcols = grid[i].length1 <= rows, cols <= 8grid[i][j]consist only of characters'C','M','F','.', and'#'.- There is only one of each character
'C','M', and'F'ingrid. 1 <= catJump, mouseJump <= 8
Solution
Approach: Topological Sorting on Game States
A game state is (mouse position, cat position, whose turn). Some states are decided immediately:
- Cat and mouse on the same cell: the cat wins.
- The cat is on the food: the cat wins.
- The mouse is on the food (and not caught): the mouse wins.
Starting from those states we work backwards. For a decided state, look at every state that can move into it (the previous mover is the other player, who jumps from a neighbouring cell reachable within its jump limit). Then:
- If the previous mover is the player who wins the current state, that previous state is also a win for them.
- Otherwise, count down the number of moves still available from the previous state. When every move from it leads to a state the mover loses, the previous state is a loss for that mover too.
Keep a queue of newly decided states, like a topological sort. When it is empty, the state at the start positions with the mouse to move is the answer. States that never get decided are draws, which the problem counts as a cat win.
Complexity: O(m^2 n^2 (m + n)) time and O(m^2 n^2) space, where m and n are the grid dimensions.
from collections import deque
class Solution:
def canMouseWin(self, grid: List[str], catJump: int, mouseJump: int) -> bool:
m, n = len(grid), len(grid[0])
cat_start = mouse_start = food = 0
dirs = (-1, 0, 1, 0, -1)
g_mouse = [[] for _ in range(m * n)]
g_cat = [[] for _ in range(m * n)]
for i, row in enumerate(grid):
for j, c in enumerate(row):
if c == "#":
continue
v = i * n + j
if c == "C":
cat_start = v
elif c == "M":
mouse_start = v
elif c == "F":
food = v
for a, b in zip(dirs, dirs[1:]):
for k in range(mouseJump + 1):
x, y = i + k * a, j + k * b
if not (0 <= x < m and 0 <= y < n and grid[x][y] != "#"):
break
g_mouse[v].append(x * n + y)
for k in range(catJump + 1):
x, y = i + k * a, j + k * b
if not (0 <= x < m and 0 <= y < n and grid[x][y] != "#"):
break
g_cat[v].append(x * n + y)
return self.calc(g_mouse, g_cat, mouse_start, cat_start, food) == 1
def calc(
self,
g_mouse: List[List[int]],
g_cat: List[List[int]],
mouse_start: int,
cat_start: int,
hole: int,
) -> int:
def get_prev_states(state):
m, c, t = state
pt = t ^ 1
pre = []
if pt == 1:
for pc in g_cat[c]:
if ans[m][pc][1] == 0:
pre.append((m, pc, pt))
else:
for pm in g_mouse[m]:
if ans[pm][c][0] == 0:
pre.append((pm, c, 0))
return pre
n = len(g_mouse)
degree = [[[0, 0] for _ in range(n)] for _ in range(n)]
for i in range(n):
for j in range(n):
degree[i][j][0] = len(g_mouse[i])
degree[i][j][1] = len(g_cat[j])
ans = [[[0, 0] for _ in range(n)] for _ in range(n)]
q = deque()
for i in range(n):
ans[hole][i][1] = 1
ans[i][hole][0] = 2
ans[i][i][1] = ans[i][i][0] = 2
q.append((hole, i, 1))
q.append((i, hole, 0))
q.append((i, i, 0))
q.append((i, i, 1))
while q:
state = q.popleft()
t = ans[state[0]][state[1]][state[2]]
for prev_state in get_prev_states(state):
pm, pc, pt = prev_state
if pt == t - 1:
ans[pm][pc][pt] = t
q.append(prev_state)
else:
degree[pm][pc][pt] -= 1
if degree[pm][pc][pt] == 0:
ans[pm][pc][pt] = t
q.append(prev_state)
return ans[mouse_start][cat_start][0]