Problem 529

Abstract / Summary

Given a minesweeper board and a click, reveal the cell and update the board according to minesweeper rules.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0529.py

class Solution:
    def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
        width  = len(board[0])
        height = len(board)

        deltas = [ [ -1, -1 ], [ -1, 0 ], [ -1, +1 ],
                   [  0, -1 ],            [  0, +1 ],
                   [ +1, -1 ], [ +1, 0 ], [ +1, +1 ] ]

        def count(x, y):
            result = 0
            for dx, dy in deltas:
                xx = x + dx
                yy = y + dy
                if 0 <= xx < width and 0 <= yy < height:
                    if board[yy][xx] in [ "M", "X" ]:
                        result += 1
            return result

        def reveal(x, y):
            # detect mine
            if board[y][x] == "M":
                board[y][x] = "X"
                return

            # already visible
            if board[y][x] != "E":
                return

            # count mines
            board[y][x] = str(count(x, y))

            # reveal surrounding squares if blank
            if board[y][x] == "0":
                board[y][x] = "B"
                for dx, dy in deltas:
                    xx = x + dx
                    yy = y + dy
                    if 0 <= xx < width and 0 <= yy < height:
                        # recursion
                        reveal(xx, yy)

        reveal(click[1], click[0])
        return board
44 lines | 1402 bytes | submitted October 13, 2023 | GitHub   15% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 69% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Breadth First Search
  • Depth First Search
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic Minesweeper reveal problem. Given a two-dimensional board of characters and a click coordinate, the algorithm updates the board according to the game rules and returns the new state. The board uses 'E' for unrevealed empty cells, 'M' for unrevealed mines, 'B' for revealed blank cells (no adjacent mines), digits '1'-'8' for revealed cells with adjacent mines, and 'X' for a revealed mine that caused the game to end. The solution follows a depth-first search (DFS) pattern, recursively expanding from the clicked cell while respecting board boundaries and already revealed cells.

Key Steps

Dimension Extraction

The first two statements compute the board dimensions, storing the horizontal size in width and the vertical size in height. These values are reused throughout the algorithm to keep boundary checks concise.

width  = len(board[0])
height = len(board)

Neighbor Offsets

A static list named deltas encodes the eight possible directions (horizontal, vertical, and diagonal). By iterating over this list, the code can examine all adjacent squares without duplicating logic.

deltas = [ [ -1, -1 ], [ -1, 0 ], [ -1, +1 ],
           [  0, -1 ],            [  0, +1 ],
           [ +1, -1 ], [ +1, 0 ], [ +1, +1 ] ]

Counting Adjacent Mines

The helper function count receives a coordinate (x, y) and iterates over deltas. For each neighbor it verifies that the neighbor lies inside the board limits and then checks whether the neighbor contains a mine ('M') or an already exploded mine ('X'). The function returns the total number of such neighbors.

def count(x, y):
    result = 0
    for dx, dy in deltas:
        xx = x + dx
        yy = y + dy
        if 0 <= xx < width and 0 <= yy < height:
            if board[yy][xx] in [ "M", "X" ]:
                result += 1
    return result

Recursive Reveal Logic

The core of the algorithm resides in the reveal function. It first checks whether the current cell is a mine. If so, the cell is turned into 'X' and the recursion stops, reflecting the game-over condition.

if board[y][x] == "M":
    board[y][x] = "X"
    return

If the cell is not unrevealed ('E'), the function returns immediately, preventing unnecessary work on already processed squares.

if board[y][x] != "E":
    return

When the cell is a fresh empty square, the function computes the number of adjacent mines using count. The result is stored as a string in the board cell.

board[y][x] = str(count(x, y))

If the count is zero, the cell is transformed into a blank reveal 'B'. The function then iterates over all eight directions, recursively invoking reveal on each neighbor that lies within the board. This expands the blank region outward until cells with non-zero adjacent mine counts are encountered.

if board[y][x] == "0":
    board[y][x] = "B"
    for dx, dy in deltas:
        xx = x + dx
        yy = y + dy
        if 0 <= xx < width and 0 <= yy < height:
            reveal(xx, yy)

Entry Point

The algorithm starts the recursion from the user-provided click coordinate. Note that the click list is ordered as [row, column], but the reveal function expects (x, y). The call swaps the indices accordingly.

reveal(click[1], click[0])
return board

Edge Cases Handled

The implementation explicitly guards against out-of-bounds access by checking 0 <= xx < width and 0 <= yy < height before any board lookup. This ensures that clicks on border cells and recursive expansions that reach the edge do not raise index errors.

When the clicked cell contains a mine, the code immediately converts it to 'X' and halts further recursion, correctly modeling the loss condition without attempting to reveal surrounding cells.

If the clicked cell is already revealed (any character other than 'E'), the function returns without modifying the board. This covers scenarios where a user clicks on a previously opened square, a situation that can arise in interactive play.

The conversion of a zero-adjacent-mine count from '0' to 'B' before recursing guarantees that the board never displays a literal '0'. This matches the conventional Minesweeper visual where blank squares are shown without a numeric label.

The count function treats both 'M' (unexploded mines) and 'X' (exploded mines) as mines when tallying adjacent threats. This subtle handling ensures that after a mine has been revealed, any neighboring blank expansion still respects the presence of that exploded mine.

Performance Optimizations

The code reuses the pre-computed width, height, and deltas values throughout the recursion, avoiding repeated length calculations or reconstruction of direction vectors. This reduces overhead in tight loops that may be invoked many times during a large blank region expansion.

By checking board[y][x] != "E" early in the reveal function, the algorithm prevents redundant work on cells that have already been processed, effectively pruning the recursion tree. This early exit eliminates unnecessary calls to count and further neighbor exploration.

The recursion only proceeds when a cell’s adjacent mine count is zero. Cells with a non-zero count are revealed once and then become leaf nodes in the recursion, preventing deeper traversal into areas that would not change the board state. This selective expansion limits the number of recursive calls to the minimal necessary set.

The count helper iterates over the fixed eight directions and performs a single boundary check per neighbor. By consolidating the mine detection into a membership test against a short list ([ "M", "X" ]), the function avoids multiple conditional branches, keeping the inner loop lightweight.

Overall, the algorithm exhibits a depth-first search pattern that visits each cell at most once, and the constant-time neighbor checks keep the per-cell work bounded, leading to efficient handling even on larger boards.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a giant grid that is like a game board filled with hidden surprises. Some spots have scary mines hidden under them, which are marked with the letter m. Other spots are empty and waiting to be cleared.

The code works like a magic wand that you tap on the board. When the wand touches a square, it first checks if there is a mine hiding there. If a mine is found, it changes to an x to show the game is finished.

If the spot is safe, the wand looks at all the squares touching it to see if any mines are nearby. It counts how many mines are hiding in those neighboring spots and writes that number down on the square. If the count is zero, it marks the square with a b and automatically taps on all the squares right next to it. This chain reaction continues until it finds spots that have numbers in them, clearing a nice path across the board as if it were uncovering a mystery.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.78 | σ = 1.55

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go TS
LeetcodeHelp C++ Java Python
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C++
linouk23 C++
lkwq007 Python
martianoff Scala
ruoru Rust
suxrobGM C#
varunu28 Java
wisdompeak C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
linouk23 C++
lkwq007 Python
martianoff Scala
ruoru Rust
suxrobGM C#
varunu28 Java
wisdompeak C++
zfang399 C++
35 links | 22 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

6 solutions   October 13, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality