#529

Minesweeper

Medium
ArrayDepth-First SearchBreadth-First SearchMatrixDepth-First SearchRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses a depth-first search (DFS) approach to reveal cells efficiently. By leveraging recursion, we can explore all adjacent cells without redundant checks, making it faster than the brute force approach.

⚙️

Algorithm

3 steps
  1. 1Step 1: If the clicked cell is a mine, change it to 'X' and return.
  2. 2Step 2: If it's an empty cell, count adjacent mines. If there are none, change it to 'B' and recursively reveal adjacent cells.
  3. 3Step 3: If there are adjacent mines, change the cell to the count.
solution.py24 lines
1def updateBoard(board, click):
2    rows, cols = len(board), len(board[0])
3    r, c = click
4    if board[r][c] == 'M':
5        board[r][c] = 'X'
6    else:
7        def countMines(r, c):
8            directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
9            count = 0
10            for dr, dc in directions:
11                nr, nc = r + dr, c + dc
12                if 0 <= nr < rows and 0 <= nc < cols and board[nr][nc] == 'M':
13                    count += 1
14            return count
15        mine_count = countMines(r, c)
16        if mine_count > 0:
17            board[r][c] = str(mine_count)
18        else:
19            board[r][c] = 'B'
20            for dr, dc in directions:
21                nr, nc = r + dr, c + dc
22                if 0 <= nr < rows and 0 <= nc < cols and board[nr][nc] == 'E':
23                    updateBoard(board, [nr, nc])
24    return board

Complexity note: The time complexity is O(n) because we explore each cell once, while the space complexity is O(n) due to the recursion stack in the worst case.

  • 1Understanding the recursive nature of the problem is crucial.
  • 2Counting adjacent mines efficiently can significantly optimize the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.