Skip to main content
Back to problems
#1728
Hard Algorithms

Cat and mouse ii

Array Math Dynamic Programming Graph Theory Topological Sort Memoization Matrix Game Theory
40.4% acceptance
Feb 25, 2026
287
48
A game is played by a cat and a mouse named Cat and Mouse. The environment is represented by a grid of size rows x cols, where each element is a wall, floor, player (Cat, Mouse), or food. Players are represented by the characters 'C'(Cat),'M'(Mouse). Floors are represented by the character '.' and can be walked on. Walls are represented by the character '#' and cannot be walked on. Food is represented by the character 'F' and can be walked on. There is only one of each character 'C', 'M', and 'F' in grid. Mouse and Cat play according to the following rules: Mouse moves first, then they take turns to move. During each turn, Cat and Mouse can jump in one of the four directions (left, right, up, down). They cannot jump over the wall nor outside of the grid. catJump, mouseJump are the maximum lengths Cat and Mouse can jump at a time, respectively. Cat and Mouse can jump less than the maximum length. Staying in the same position is allowed. Mouse can jump over Cat. The game can end in 4 ways: If Cat occupies the same position as Mouse, Cat wins. If Cat reaches the food first, Cat wins. If Mouse reaches the food first, Mouse wins. If Mouse cannot get to the food within 1000 turns, Cat wins. Given a rows x cols matrix grid and two integers catJump and mouseJump, return true if Mouse can win the game if both Cat and Mouse play optimally, otherwise return false.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn can_mouse_win(grid: Vec<String>, cat_jump: i32, mouse_jump: i32) -> bool {
    let rows = grid.len() as i32;
    let cols = grid[0].len() as i32;
    let bytes: Vec<Vec<u8>> = grid.iter().map(|r| r.bytes().collect()).collect();
    let max_turns = (rows * cols * 2) as usize;

    let mut mouse = 0usize;
    let mut cat = 0usize;
    let mut food = 0usize;
    for i in 0..rows {
      for j in 0..cols {
        let idx = (i * cols + j) as usize;
        match bytes[i as usize][j as usize] {
          b'M' => mouse = idx,
          b'C' => cat = idx,
          b'F' => food = idx,
          _ => {}
        }
      }
    }

    let total = (rows * cols) as usize;
    // dp[mouse][cat][turn]: 0=unvisited, 1=mouse_wins, 2=cat_wins
    let mut dp = vec![vec![vec![0u8; max_turns + 1]; total]; total];

    Self::solve(&bytes, &mut dp, mouse, cat, food, 0, max_turns, rows, cols, mouse_jump, cat_jump) == 1
  }

  fn solve(
    grid: &[Vec<u8>], dp: &mut Vec<Vec<Vec<u8>>>,
    mouse: usize, cat: usize, food: usize,
    turn: usize, max_turns: usize,
    rows: i32, cols: i32, mouse_jump: i32, cat_jump: i32,
  ) -> u8 {
    if turn >= max_turns || cat == food || mouse == cat { return 2; }
    if mouse == food { return 1; }
    if dp[mouse][cat][turn] != 0 { return dp[mouse][cat][turn]; }
    // Mark in-progress as cat_wins (handles cycles: cat wins by timeout)
    dp[mouse][cat][turn] = 2;

    const DIRS: [(i32, i32); 4] = [(0, 1), (0, -1), (1, 0), (-1, 0)];

    if turn % 2 == 0 {
      // Mouse's turn: mouse wants to win (any winning move suffices)
      let (mr, mc) = ((mouse as i32) / cols, (mouse as i32) % cols);
      for &(dr, dc) in &DIRS {
        for jump in 0..=mouse_jump {
          let nr = mr + dr * jump;
          let nc = mc + dc * jump;
          if nr < 0 || nr >= rows || nc < 0 || nc >= cols { break; }
          if grid[nr as usize][nc as usize] == b'#' { break; }
          let nm = (nr * cols + nc) as usize;
          if Self::solve(grid, dp, nm, cat, food, turn + 1, max_turns, rows, cols, mouse_jump, cat_jump) == 1 {
            dp[mouse][cat][turn] = 1;
            return 1;
          }
        }
      }
    } else {
      // Cat's turn: cat wants to prevent mouse win (any preventing move suffices)
      let (cr, cc) = ((cat as i32) / cols, (cat as i32) % cols);
      let mut all_mouse_wins = true;
      'outer: for &(dr, dc) in &DIRS {
        for jump in 0..=cat_jump {
          let nr = cr + dr * jump;
          let ncc = cc + dc * jump;
          if nr < 0 || nr >= rows || ncc < 0 || ncc >= cols { break; }
          if grid[nr as usize][ncc as usize] == b'#' { break; }
          let nc_pos = (nr * cols + ncc) as usize;
          let r = Self::solve(grid, dp, mouse, nc_pos, food, turn + 1, max_turns, rows, cols, mouse_jump, cat_jump);
          if r == 2 {
            all_mouse_wins = false;
            dp[mouse][cat][turn] = 2;
            break 'outer;
          }
          if r != 1 { all_mouse_wins = false; }
        }
      }
      if all_mouse_wins {
        dp[mouse][cat][turn] = 1;
        return 1;
      }
    }

    dp[mouse][cat][turn]
  }
}