Approach
Breadth-first search
For Cat and Mouse, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 58 lines of Python from the credited upstream file 913.py.
- The implementation visibly relies on sequence storage, work queue.
- No explicit loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from enum import IntEnum2 3 4class State(IntEnum):5 DRAW = 06 MOUSE_WIN = 17 CAT_WIN = 28 9 10class Solution:11 def catMouseGame(self, graph: list[list[int]]) -> int:12 n = len(graph)13 14 15 states = [[[0] * 2 for _ in range(n)] for _ in range(n)]16 outDegree = [[[0] * 2 for _ in range(n)] for _ in range(n)]17 q = collections.deque() 18 19 for cat in range(n):20 for mouse in range(n):21 outDegree[cat][mouse][0] = len(graph[mouse])22 outDegree[cat][mouse][1] = len(graph[cat]) - graph[cat].count(0)23 24 25 for cat in range(1, n):26 for move in range(2):27 28 states[cat][0][move] = int(State.MOUSE_WIN)29 q.append((cat, 0, move, int(State.MOUSE_WIN)))30 31 states[cat][cat][move] = int(State.CAT_WIN)32 q.append((cat, cat, move, int(State.CAT_WIN)))33 34 while q:35 cat, mouse, move, state = q.popleft()36 if cat == 2 and mouse == 1 and move == 0:37 return state38 prevMove = move ^ 139 for prev in graph[cat if prevMove else mouse]:40 prevCat = prev if prevMove else cat41 if prevCat == 0: 42 continue43 prevMouse = mouse if prevMove else prev44 45 if states[prevCat][prevMouse][prevMove]:46 continue47 if (prevMove == 0 and state == int(State.MOUSE_WIN) or48 prevMove == 1 and state == int(State.CAT_WIN)):49 states[prevCat][prevMouse][prevMove] = state50 q.append((prevCat, prevMouse, prevMove, state))51 else:52 outDegree[prevCat][prevMouse][prevMove] -= 153 if outDegree[prevCat][prevMouse][prevMove] == 0:54 states[prevCat][prevMouse][prevMove] = state55 q.append((prevCat, prevMouse, prevMove, state))56 57 return states[2][1][0]58