Problem solution · Java

Cat and Mouse

Cat and Mouse: a Java solution using breadth-first search. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Breadth-first search
Source
walkccc LeetCode Solutions
Length
58 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Model each valid configuration as a state and each legal move as an edge.
  2. Seed the queue with the starting state and mark it immediately.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeCat and Mouse · JavaJava
Use this to learn the idea, then write your own version.
enum State { DRAW, MOUSE_WIN, CAT_WIN } class Solution {  public int catMouseGame(int[][] graph) {    final int n = graph.length;    // result of (cat, mouse, move)    // move := 0 (mouse) / 1 (cat)    int[][][] states = new int[n][n][2];    int[][][] outDegree = new int[n][n][2];    Queue<int[]> q = new ArrayDeque<>();     for (int cat = 0; cat < n; ++cat)      for (int mouse = 0; mouse < n; ++mouse) {        outDegree[cat][mouse][0] = graph[mouse].length;        outDegree[cat][mouse][1] =            graph[cat].length - (Arrays.stream(graph[cat]).anyMatch(v -> v == 0) ? 1 : 0);      }     // Start from the states s.t. the winner can be determined.    for (int cat = 1; cat < n; ++cat)      for (int move = 0; move < 2; ++move) {        // Mouse is in the hole.        states[cat][0][move] = State.MOUSE_WIN.ordinal();        q.offer(new int[] {cat, 0, move, State.MOUSE_WIN.ordinal()});        // Cat catches mouse.        states[cat][cat][move] = State.CAT_WIN.ordinal();        q.offer(new int[] {cat, cat, move, State.CAT_WIN.ordinal()});      }     while (!q.isEmpty()) {      final int cat = q.peek()[0];      final int mouse = q.peek()[1];      final int move = q.peek()[2];      final int state = q.poll()[3];      if (cat == 2 && mouse == 1 && move == 0)        return state;      final int prevMove = move ^ 1;      for (final int prev : graph[prevMove == 0 ? mouse : cat]) {        final int prevCat = prevMove == 0 ? cat : prev;        if (prevCat == 0) // invalid          continue;        final int prevMouse = prevMove == 0 ? prev : mouse;        // The state has been determined.        if (states[prevCat][prevMouse][prevMove] > 0)          continue;        if (prevMove == 0 && state == State.MOUSE_WIN.ordinal() ||            prevMove == 1 && state == State.CAT_WIN.ordinal() ||            --outDegree[prevCat][prevMouse][prevMove] == 0) {          states[prevCat][prevMouse][prevMove] = state;          q.offer(new int[] {prevCat, prevMouse, prevMove, state});        }      }    }     return states[2][1][0];  }} 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗