Cat and Mouse - Problem
Imagine a thrilling chase game between a clever Cat and a sneaky Mouse on a connected graph! This is a classic game theory problem that tests your understanding of optimal strategy and dynamic programming.
The Setup:
- The graph is represented as
graph[a]- a list of all nodes connected to nodea - Mouse starts at node 1 and moves first
- Cat starts at node 2 and moves second
- There's a safe hole at node 0 where the mouse can escape
The Rules:
- Players alternate turns, each must move along an edge to a connected node
- The Cat cannot enter the hole (node 0)
- Cat wins if it catches the mouse (same node)
- Mouse wins if it reaches the hole (node 0)
- It's a draw if the same game state repeats
Your Goal: Assuming both players play optimally, determine the winner!
Return 1 if mouse wins, 2 if cat wins, or 0 for a draw.
Input & Output
example_1.py โ Simple Triangle
$
Input:
graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]
โบ
Output:
0
๐ก Note:
Mouse starts at 1, Cat at 2. Both players play optimally. The mouse can move to 3, and regardless of cat's moves, the game leads to a draw situation where positions repeat.
example_2.py โ Mouse Can Win
$
Input:
graph = [[1,3],[0,2],[1,3],[0,2]]
โบ
Output:
1
๐ก Note:
Mouse at 1 can immediately move to 0 (the hole) and win, regardless of what the cat does from position 2.
example_3.py โ Cat Dominates
$
Input:
graph = [[1,2,3],[0,2],[0,1],[0]]
โบ
Output:
2
๐ก Note:
The cat at position 2 has strategic advantage and can force a win by controlling key positions and eventually catching the mouse.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Terminal States
Mark states where mouse reaches hole (mouse wins) or cat catches mouse (cat wins)
2
Build State Graph
Create a graph of all possible game states (mouse pos, cat pos, turn)
3
Propagate Backwards
Use BFS to determine outcomes of parent states based on child outcomes
4
Apply Minimax Logic
Current player wins if any move leads to victory; loses if all moves lead to opponent victory
Key Takeaway
๐ฏ Key Insight: Use backwards induction from terminal states - if a player has any winning move available, they'll take it; if all moves lead to opponent wins, they lose; otherwise it's a draw.
Time & Space Complexity
Time Complexity
O(Nยณ ร 2^(Nยฒ))
Nยณ possible states times exponential branching factor due to lack of memoization
โ Linear Growth
Space Complexity
O(Nยฒ)
Recursion depth proportional to number of moves before cycle detection
โ Linear Space
Constraints
- 3 โค graph.length โค 50
- 1 โค graph[i].length < graph.length
- 0 โค graph[i][j] < graph.length
- graph[i][j] โ i
- graph[i] is unique
- The mouse and the cat can always move
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code