Problem
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, mouseJump
are 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 returnfalse
.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
rows == grid.length
cols = grid[i].length
Solution
Method 1 – Game Theory with DFS and Memoization
Intuition: This is a two-player perfect information game. Each state is defined by the positions of the mouse and cat, whose turn it is, and the number of turns taken. The mouse wins if it reaches the food before the cat or before 1000 turns; the cat wins if it catches the mouse or reaches the food first. We use DFS to explore all possible moves and memoization to avoid recalculating the same state.
Approach:
- Parse the grid to find the initial positions of the mouse, cat, and food.
- Use DFS with memoization to simulate all possible moves for both players.
- For each state, check for base cases:
- Cat catches mouse (same cell): Cat wins.
- Cat reaches food: Cat wins.
- Mouse reaches food: Mouse wins.
- More than 1000 moves: Cat wins.
- For each move, try all possible jump distances in four directions, including staying in place.
- Alternate turns and recursively check if the current player can force a win.
- Memoize results for each state to avoid recomputation.
Code
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^5)
, wheren
is the number of cells (due to positions and turn count). - 🧺 Space complexity:
O(n^5)
for memoization.