Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #529: Minesweeper

In this guide, we solve Leetcode #529 Minesweeper in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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.

Quick Facts

  • Difficulty: Medium
  • Premium: No
  • Tags: Depth-First Search, Breadth-First Search, Array, Matrix

Intuition

We need to explore a structure deeply before backing up, which suits DFS.

DFS keeps local context on the call stack and is easy to implement recursively.

Approach

Define a recursive DFS that carries the necessary state.

Combine child results as the recursion unwinds.

Steps:

  • Define a recursive DFS with state.
  • Visit children and combine results.
  • Return the final aggregation.

Example

Input: board = [["E","E","E","E","E"],["E","E","M","E","E"],["E","E","E","E","E"],["E","E","E","E","E"]], click = [3,0] Output: [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]]

Python Solution

class Solution: def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: def dfs(i: int, j: int): cnt = 0 for x in range(i - 1, i + 2): for y in range(j - 1, j + 2): if 0 <= x < m and 0 <= y < n and board[x][y] == "M": cnt += 1 if cnt: board[i][j] = str(cnt) else: board[i][j] = "B" for x in range(i - 1, i + 2): for y in range(j - 1, j + 2): if 0 <= x < m and 0 <= y < n and board[x][y] == "E": dfs(x, y) m, n = len(board), len(board[0]) i, j = click if board[i][j] == "M": board[i][j] = "X" else: dfs(i, j) return board

Complexity

The time complexity is O(V+E). The space complexity is O(V).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy