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 Java from the credited upstream file 913.java.
- The implementation visibly relies on sequence storage, work queue.
- 6 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.
1enum State { DRAW, MOUSE_WIN, CAT_WIN }2 3class Solution {4 public int catMouseGame(int[][] graph) {5 final int n = graph.length;6 7 8 int[][][] states = new int[n][n][2];9 int[][][] outDegree = new int[n][n][2];10 Queue<int[]> q = new ArrayDeque<>();11 12 for (int cat = 0; cat < n; ++cat)13 for (int mouse = 0; mouse < n; ++mouse) {14 outDegree[cat][mouse][0] = graph[mouse].length;15 outDegree[cat][mouse][1] =16 graph[cat].length - (Arrays.stream(graph[cat]).anyMatch(v -> v == 0) ? 1 : 0);17 }18 19 20 for (int cat = 1; cat < n; ++cat)21 for (int move = 0; move < 2; ++move) {22 23 states[cat][0][move] = State.MOUSE_WIN.ordinal();24 q.offer(new int[] {cat, 0, move, State.MOUSE_WIN.ordinal()});25 26 states[cat][cat][move] = State.CAT_WIN.ordinal();27 q.offer(new int[] {cat, cat, move, State.CAT_WIN.ordinal()});28 }29 30 while (!q.isEmpty()) {31 final int cat = q.peek()[0];32 final int mouse = q.peek()[1];33 final int move = q.peek()[2];34 final int state = q.poll()[3];35 if (cat == 2 && mouse == 1 && move == 0)36 return state;37 final int prevMove = move ^ 1;38 for (final int prev : graph[prevMove == 0 ? mouse : cat]) {39 final int prevCat = prevMove == 0 ? cat : prev;40 if (prevCat == 0) 41 continue;42 final int prevMouse = prevMove == 0 ? prev : mouse;43 44 if (states[prevCat][prevMouse][prevMove] > 0)45 continue;46 if (prevMove == 0 && state == State.MOUSE_WIN.ordinal() ||47 prevMove == 1 && state == State.CAT_WIN.ordinal() ||48 --outDegree[prevCat][prevMouse][prevMove] == 0) {49 states[prevCat][prevMouse][prevMove] = state;50 q.offer(new int[] {prevCat, prevMouse, prevMove, state});51 }52 }53 }54 55 return states[2][1][0];56 }57}58