Skip to main content
Back to problems
#529
Medium Algorithms

Minesweeper

Array Depth-First Search Breadth-First Search Matrix
68.6% acceptance
Feb 19, 2026
2083
1088
Let's play the minesweeper game (Wikipedia, online game)! You are given an m x n char matrix board representing the game board where: 'M' represents an unrevealed mine, 'E' represents an unrevealed empty square, 'B' represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals), digit ('1' to '8') represents how many mines are adjacent to this revealed square, and 'X' represents a revealed mine. You are also given an integer array click where click = [clickr, clickc] represents the next click position among all the unrevealed squares ('M' or 'E'). Return the board after revealing this position according to the following rules: If a mine 'M' is revealed, then the game is over. You should change it to 'X'. If an empty square 'E' with no adjacent mines is revealed, then change it to a revealed blank 'B' and all of its adjacent unrevealed squares should be revealed recursively. If an empty square 'E' with at least one adjacent mine is revealed, then change it to a digit ('1' to '8') representing the number of adjacent mines. Return the board when no more squares will be revealed.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn update_board(mut board: Vec<Vec<char>>, click: Vec<i32>) -> Vec<Vec<char>> {
    let r = click[0] as usize;
    let c = click[1] as usize;
    if board[r][c] == 'M' {
      board[r][c] = 'X';
      return board;
    }
    let m = board.len();
    let n = board[0].len();
    fn dfs(board: &mut Vec<Vec<char>>, r: usize, c: usize, m: usize, n: usize) {
      let dirs: [(i32, i32); 8] = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)];
      let mines = dirs.iter().filter(|&&(dr, dc)| {
        let nr = r as i32 + dr; let nc = c as i32 + dc;
        nr >= 0 && nr < m as i32 && nc >= 0 && nc < n as i32 && board[nr as usize][nc as usize] == 'M'
      }).count() as i32;
      if mines > 0 {
        board[r][c] = (b'0' + mines as u8) as char;
      } else {
        board[r][c] = 'B';
        for &(dr, dc) in &dirs {
          let nr = r as i32 + dr; let nc = c as i32 + dc;
          if nr >= 0 && nr < m as i32 && nc >= 0 && nc < n as i32 && board[nr as usize][nc as usize] == 'E' {
            dfs(board, nr as usize, nc as usize, m, n);
          }
        }
      }
    }
    dfs(&mut board, r, c, m, n);
    board
  }
}