KatInterview

949. Cat and Mouse

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Game Theory with Back-propagation (Topological Sort)

1. Problem Analysis

Solution

Cat and Mouse in Python

from collections import deque

class Solution:
    def catMouseGame(self, graph: list[list[int]]) -> int:
        n = len(graph)
        DRAW, MOUSE_WIN, CAT_WIN = 0, 1, 2
        
        # State: (mouse_pos, cat_pos, turn)
        # turn 0: mouse, 1: cat
        # color: 0: draw, 1: mouse win, 2: cat win
        color = [[[DRAW] * 2 for _ in range(n)] for _ in range(n)]
        
        # out_degree[m][c][t] = number of next states that are still DRAW
        out_degree = [[[0] * 2 for _ in range(n)] for _ in range(n)]
        
        for m in range(n):
            for c in range(n):
                out_degree[m][c][0] = len(graph[m])
                for neighbor in graph[c]:
                    if neighbor != 0:
                        out_degree[m][c][1] += 1
        
        q = deque()
        
        # Initialize terminal states
        for c in range(1, n):
            # Mouse at hole (node 0) -> Mouse wins
            color[0][c][0] = MOUSE_WIN
            q.append((0, c, 0))
            color[0][c][1] = MOUSE_WIN
            q.append((0, c, 1))
        
        for p in range(1, n):
            # Cat at same position as mouse -> Cat wins
            color[p][p][0] = CAT_WIN
            q.append((p, p, 0))
            color[p][p][1] = CAT_WIN
            q.append((p, p, 1))
            
        # Propagate colors
        while q:
            m, c, t = q.popleft()
            outcome = color[m][c][t]
            
            # Find parent states and update them
            if t == 1:  # Current turn is cat, so previous turn was mouse
                # Parent state is (prev_m, c, 0)
                for prev_m in graph[m]:
                    if color[prev_m][c][0] == DRAW:
                        if outcome == MOUSE_WIN:
                            color[prev_m][c][0] = MOUSE_WIN
                            q.append((prev_m, c, 0))
                        else: # outcome == CAT_WIN
                            out_degree[prev_m][c][0] -= 1
                            if out_degree[prev_m][c][0] == 0:
                                color[prev_m][c][0] = CAT_WIN
                                q.append((prev_m, c, 0))
            else:  # Current turn is mouse, so previous turn was cat
                # Parent state is (m, prev_c, 1)
                for prev_c in graph[c]:
                    if prev_c == 0:
                        continue
                    if color[m][prev_c][1] == DRAW:
                        if outcome == CAT_WIN:
                            color[m][prev_c][1] = CAT_WIN
                            q.append((m, prev_c, 1))
                        else: # outcome == MOUSE_WIN
                            out_degree[m][prev_c][1] -= 1
                            if out_degree[m][prev_c][1] == 0:
                                color[m][prev_c][1] = MOUSE_WIN
                                q.append((m, prev_c, 1))
                                
        return color[1][2][0]

Cat and Mouse in Java

class Solution {
    public int catMouseGame(int[][] graph) {
        int n = graph.length;
        final int DRAW = 0, MOUSE_WIN = 1, CAT_WIN = 2;

        // State: (mouse_pos, cat_pos, turn)
        // turn 0: mouse, 1: cat
        // color: 0: draw, 1: mouse win, 2: cat win
        int[][][] color = new int[n][n][2];
        // out_degree[m][c][t] = number of next states that are still DRAW
        int[][][] out_degree = new int[n][n][2];

        Queue<int[]> q = new LinkedList<>();

        // Initialize out_degrees and terminal states
        for (int m = 0; m < n; m++) {
            for (int c = 0; c < n; c++) {
                out_degree[m][c][0] = graph[m].length;
                for (int neighbor : graph[c]) {
                    if (neighbor != 0) {
                        out_degree[m][c][1]++;
                    }
                }
            }
        }

        // Initialize terminal states
        for (int c = 1; c < n; c++) {
            // Mouse at hole (node 0) -> Mouse wins
            color[0][c][0] = MOUSE_WIN;
            q.offer(new int[]{0, c, 0});
            color[0][c][1] = MOUSE_WIN;
            q.offer(new int[]{0, c, 1});
        }

        for (int p = 1; p < n; p++) {
            // Cat at same position as mouse -> Cat wins
            color[p][p][0] = CAT_WIN;
            q.offer(new int[]{p, p, 0});
            color[p][p][1] = CAT_WIN;
            q.offer(new int[]{p, p, 1});
        }

        // Propagate colors
        while (!q.isEmpty()) {
            int[] state = q.poll();
            int m = state[0], c = state[1], t = state[2];
            int outcome = color[m][c][t];
            
            // Find parent states and update them
            if (t == 1) { // Current turn is cat, so previous turn was mouse
                // Parent state is (prev_m, c, 0)
                for (int prev_m : graph[m]) {
                    if (color[prev_m][c][0] == DRAW) {
                        if (outcome == MOUSE_WIN) {
                            color[prev_m][c][0] = MOUSE_WIN;
                            q.offer(new int[]{prev_m, c, 0});
                        } else {
                            out_degree[prev_m][c][0]--;
                            if (out_degree[prev_m][c][0] == 0) {
                                color[prev_m][c][0] = CAT_WIN;
                                q.offer(new int[]{prev_m, c, 0});
                            }
                        }
                    }
                }
            } else { // Current turn is mouse, so previous turn was cat
                // Parent state is (m, prev_c, 1)
                for (int prev_c : graph[c]) {
                    if (prev_c == 0) continue;
                    if (color[m][prev_c][1] == DRAW) {
                        if (outcome == CAT_WIN) {
                            color[m][prev_c][1] = CAT_WIN;
                            q.offer(new int[]{m, prev_c, 1});
                        } else {
                            out_degree[m][prev_c][1]--;
                            if (out_degree[m][prev_c][1] == 0) {
                                color[m][prev_c][1] = MOUSE_WIN;
                                q.offer(new int[]{m, prev_c, 1});
                            }
                        }
                    }
                }
            }
        }

        return color[1][2][0];
    }
}

Cat and Mouse in C++

class Solution {
public:
    int catMouseGame(vector<vector<int>>& graph) {
        int n = graph.size();
        // Constants for outcomes
        const int DRAW = 0, MOUSE_WIN = 1, CAT_WIN = 2;

        // State: (mouse_pos, cat_pos, turn)
        // turn 0: mouse, 1: cat
        // color: 0: draw, 1: mouse win, 2: cat win
        vector<vector<vector<int>>> color(n, vector<vector<int>>(n, vector<int>(2, DRAW)));
        
        // out_degree[m][c][t] = number of next states that are still DRAW
        vector<vector<vector<int>>> out_degree(n, vector<vector<int>>(n, vector<int>(2, 0)));

        queue<tuple<int, int, int>> q;

        // Initialize out_degrees and terminal states
        for (int m = 0; m < n; ++m) {
            for (int c = 0; c < n; ++c) {
                out_degree[m][c][0] = graph[m].size();
                for (int neighbor : graph[c]) {
                    if (neighbor != 0) {
                        out_degree[m][c][1]++;
                    }
                }
            }
        }

        // Initialize terminal states
        for (int c = 1; c < n; ++c) {
            // Mouse at hole (node 0) -> Mouse wins
            color[0][c][0] = MOUSE_WIN;
            q.push({0, c, 0});
            color[0][c][1] = MOUSE_WIN;
            q.push({0, c, 1});
        }

        for (int p = 1; p < n; ++p) {
            // Cat at same position as mouse -> Cat wins
            color[p][p][0] = CAT_WIN;
            q.push({p, p, 0});
            color[p][p][1] = CAT_WIN;
            q.push({p, p, 1});
        }

        // Propagate colors
        while (!q.empty()) {
            auto [m, c, t] = q.front();
            q.pop();
            int outcome = color[m][c][t];
            
            // Find parent states and update them
            if (t == 1) { // Current turn is cat, so previous turn was mouse
                // Parent state is (prev_m, c, 0) where mouse moved from prev_m to m
                for (int prev_m : graph[m]) {
                    if (color[prev_m][c][0] == DRAW) {
                        if (outcome == MOUSE_WIN) {
                            // Mouse found a winning move from prev_m
                            color[prev_m][c][0] = MOUSE_WIN;
                            q.push({prev_m, c, 0});
                        } else { // outcome == CAT_WIN
                            // One of mouse's moves from prev_m is a losing move
                            out_degree[prev_m][c][0]--;
                            if (out_degree[prev_m][c][0] == 0) {
                                // All of mouse's moves are losing moves
                                color[prev_m][c][0] = CAT_WIN;
                                q.push({prev_m, c, 0});
                            }
                        }
                    }
                }
            } else { // Current turn is mouse, so previous turn was cat
                // Parent state is (m, prev_c, 1) where cat moved from prev_c to c
                for (int prev_c : graph[c]) {
                    if (prev_c == 0) continue; // Cat cannot move from hole
                    if (color[m][prev_c][1] == DRAW) {
                        if (outcome == CAT_WIN) {
                            // Cat found a winning move from prev_c
                            color[m][prev_c][1] = CAT_WIN;
                            q.push({m, prev_c, 1});
                        } else { // outcome == MOUSE_WIN
                            // One of cat's moves from prev_c is a losing move
                            out_degree[m][prev_c][1]--;
                            if (out_degree[m][prev_c][1] == 0) {
                                // All of cat's moves are losing moves
                                color[m][prev_c][1] = MOUSE_WIN;
                                q.push({m, prev_c, 1});
                            }
                        }
                    }
                }
            }
        }

        return color[1][2][0];
    }
};

Cat and Mouse in TypeScript

function catMouseGame(graph: number[][]): number {
    const n = graph.length;
    const DRAW = 0, MOUSE_WIN = 1, CAT_WIN = 2;

    // State: [mouse_pos, cat_pos, turn]
    // turn 0: mouse, 1: cat
    // color: 0: draw, 1: mouse win, 2: cat win
    const color: number[][][] = Array(n).fill(0).map(() => Array(n).fill(0).map(() => Array(2).fill(DRAW)));
    const out_degree: number[][][] = Array(n).fill(0).map(() => Array(n).fill(0).map(() => Array(2).fill(0)));

    const q: number[][] = [];

    // Initialize out_degrees and terminal states
    for (let m = 0; m < n; m++) {
        for (let c = 0; c < n; c++) {
            out_degree[m][c][0] = graph[m].length;
            for (const neighbor of graph[c]) {
                if (neighbor !== 0) {
                    out_degree[m][c][1]++;
                }
            }
        }
    }

    // Initialize terminal states
    for (let c = 1; c < n; c++) {
        // Mouse at hole (node 0) -> Mouse wins
        color[0][c][0] = MOUSE_WIN;
        q.push([0, c, 0]);
        color[0][c][1] = MOUSE_WIN;
        q.push([0, c, 1]);
    }

    for (let p = 1; p < n; p++) {
        // Cat at same position as mouse -> Cat wins
        color[p][p][0] = CAT_WIN;
        q.push([p, p, 0]);
        color[p][p][1] = CAT_WIN;
        q.push([p, p, 1]);
    }

    // Propagate colors
    let head = 0;
    while (head < q.length) {
        const [m, c, t] = q[head++];
        const outcome = color[m][c][t];

        // Find parent states and update them
        if (t === 1) { // Current turn is cat, so previous turn was mouse
            // Parent state is (prev_m, c, 0)
            for (const prev_m of graph[m]) {
                if (color[prev_m][c][0] === DRAW) {
                    if (outcome === MOUSE_WIN) {
                        color[prev_m][c][0] = MOUSE_WIN;
                        q.push([prev_m, c, 0]);
                    } else {
                        out_degree[prev_m][c][0]--;
                        if (out_degree[prev_m][c][0] === 0) {
                            color[prev_m][c][0] = CAT_WIN;
                            q.push([prev_m, c, 0]);
                        }
                    }
                }
            }
        } else { // Current turn is mouse, so previous turn was cat
            // Parent state is (m, prev_c, 1)
            for (const prev_c of graph[c]) {
                if (prev_c === 0) continue;
                if (color[m][prev_c][1] === DRAW) {
                    if (outcome === CAT_WIN) {
                        color[m][prev_c][1] = CAT_WIN;
                        q.push([m, prev_c, 1]);
                    } else {
                        out_degree[m][prev_c][1]--;
                        if (out_degree[m][prev_c][1] === 0) {
                            color[m][prev_c][1] = MOUSE_WIN;
                            q.push([m, prev_c, 1]);
                        }
                    }
                }
            }
        }
    }

    return color[1][2][0];
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.