Deterministic Mine Grid Plus Letter-Path Check
Trees & GraphsAuto-graded · 18 test casesLast updated
Build a mine-count grid with mines in row-major order, then use DFS backtracking to check whether a word can be traced through a separate letter grid.
Write one function that does two independent jobs on two different grids and returns both results.
Job 1: Mine-count grid
You are given rows, cols and mine_count. Build a rows x cols grid of single-character strings as follows:
- Place mines in the first
mine_countcells in row-major order. That means row 0 from left to right, then row 1 from left to right, and so on. A mine cell holds the string"M". - Every other cell holds the number of mines among its up-to-8 neighbours (horizontal, vertical and diagonal), written as a single-digit string from
"0"to"8".
Mine placement is fixed rather than random, so the output is fully determined by the inputs.
Job 2: Word tracing
You are also given grid, a 2D list of strings, and a string target. Decide whether target can be spelled by walking through grid:
- The first character is read from any cell. Each following character is read from a cell directly above, below, left or right of the previous one.
- A cell may be used at most once within one walk.
- A cell matches a character only if its string equals that single character exactly. A cell holding an empty string
""matches nothing. - If
targetis the empty string, the answer isTrue. - If
targetis non-empty andgridhas no rows or its first row is empty, the answer isFalse. - If
targetis longer than the number of cells (len(grid) * len(grid[0])), the answer isFalse.
The grid dimensions rows and cols from Job 1 have no relation to the shape of grid in Job 2.
Return value
Return a dictionary with exactly two keys:
"minesweeper": the grid from Job 1, as a list of lists of strings."exists": a boolean, the answer to Job 2.
Constraints
1 <= rows, cols <= 500 <= mine_count <= rows * cols1 <= len(target) <= 100(the empty-string rule above is still applied defensively)- Each cell of
gridis a string, possibly empty, andgridis rectangular.
Examples
Example 1
Input: build_board_and_find_word(3, 3, 2, [['A', 'B', 'C'], ['D', 'E', 'F']], 'ABED')
Output: {'minesweeper': [['M', 'M', '1'], ['2', '2', '1'], ['0', '0', '0']], 'exists': True}
Example 2
Input: build_board_and_find_word(1, 1, 0, [['A']], 'A')
Output: {'minesweeper': [['0']], 'exists': True}
Example 3
Input: build_board_and_find_word(2, 2, 4, [['A', 'B'], ['C', 'D']], 'ABCD')
Output: {'minesweeper': [['M', 'M'], ['M', 'M']], 'exists': False}
Hints
Hint 1
For the mine grid, first mark the first mine_count cells in row-major order. Cell index i maps to row i // cols and column i % cols.
Hint 2
For every non-mine cell, loop over the 8 offsets (dr, dc) except (0, 0), check bounds, and count neighbours that are 'M'. Convert the count to a string.
Hint 3
For the word search, run a DFS from every cell. At depth i the current cell must match target[i]. Keep a visited marker for the current path and clear it when you backtrack.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The two jobs are independent, so solve each separately and combine the results in a dictionary.
Job 1: Mine-count grid
- Create a boolean grid and mark the first
mine_countcells in row-major order. Flat indeximaps to(i // cols, i % cols). - For each cell, if it is a mine, write
"M". - Otherwise, check the 8 surrounding offsets, skipping
(0, 0)and anything out of bounds. Count the neighbours that are mines and write the count as a string.
This is correct because each non-mine cell's value is, by definition, the number of in-bounds neighbours that are mines. Mine placement is fixed, so there is nothing to randomise. The edge cases mine_count = 0 (all "0") and mine_count = rows * cols (all "M") need no special handling.
Job 2: Word tracing
- Handle the trivial cases first. An empty target gives
True. A non-empty target with an empty grid givesFalse. A target longer than the number of cells givesFalse. - Otherwise run a DFS with backtracking from every cell. At depth
i, the current cell must be in bounds, unused on the current path, and equal totarget[i]. Ifireacheslen(target), a full match has been found. - Mark the cell as used before exploring its four neighbours and unmark it afterwards, so different branches and start cells see a clean board.
This is correct because the DFS tries every simple path whose letters follow the target prefix. The used-marker prevents cell reuse within one path, and backtracking ensures no path is wrongly blocked by an abandoned branch. A cell holding "" never equals a one-character string, so it acts as a wall.
Complexity
Let L = len(target), and let h x w be the size of grid.
- Job 1: time
O(rows * cols), spaceO(rows * cols). - Job 2: time
O(h * w * 3^L)in the worst case. Each start cell has 4 first moves and at most 3 later moves, since the previous cell is already used. Early mismatches prune most branches in practice. Space isO(h * w)for the visited matrix plusO(L)for the recursion stack, andL <= 100fits within Python's default recursion limit.
Reference solution
from typing import Dict, List
def build_board_and_find_word(rows: int, cols: int, mine_count: int, grid: List[List[str]], target: str) -> Dict[str, object]:
# ---- Job 1: mine-count grid ----
mines = [[False] * cols for _ in range(rows)]
for idx in range(mine_count):
r, c = divmod(idx, cols)
mines[r][c] = True
board_out = [["0"] * cols for _ in range(rows)]
for r in range(rows):
for c in range(cols):
if mines[r][c]:
board_out[r][c] = "M"
continue
count = 0
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
if dr == 0 and dc == 0:
continue
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and mines[nr][nc]:
count += 1
board_out[r][c] = str(count)
# ---- Job 2: word tracing ----
if not grid or not grid[0] or not target:
found = not target
else:
h = len(grid)
w = len(grid[0])
if len(target) > h * w:
found = False
else:
used = [[False] * w for _ in range(h)]
L = len(target)
def dfs(r: int, c: int, i: int) -> bool:
if i == L:
return True
if r < 0 or r >= h or c < 0 or c >= w:
return False
if used[r][c] or grid[r][c] != target[i]:
return False
used[r][c] = True
ok = False
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
if dfs(r + dr, c + dc, i + 1):
ok = True
break
used[r][c] = False
return ok
found = False
for r in range(h):
for c in range(w):
if dfs(r, c, 0):
found = True
break
if found:
break
return {"minesweeper": board_out, "exists": found}