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.
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
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code