You are tasked with building a minesweeper board. Given the number of rows rows, the number of columns cols, and a mine count n, your job is to place exactly n mines on distinct, randomly chosen cells of a rows x cols grid. Return (or print) the resulting 2D array.
This is not an object-oriented design question. The core algorithm is concise, so interviewers typically focus on code quality: minimizing variables, avoiding redundant data structures, and keeping control flow simple. The main challenge is selecting n distinct random cells cleanly.
Assume the following:
0 <= n <= rows * cols, so the request is always satisfiable.1 (or '*') and an empty cell by 0 (or '.').n mines on distinct cells is acceptable; the output is random.n guaranteed to be at most rows * cols? If not, should we cap it or reject the input?n distinct mines sufficient? Uniformity affects which approach is cleanest.Since the output is random, the following are just possible valid boards for illustration.
Input:
rows = 3, cols = 3, n = 2
One possible output:
[
[0, 1, 0],
[0, 0, 0],
[1, 0, 0]
]
Explanation: Two mines are placed at distinct cells (0,1) and (2,0); all other cells are empty. Any arrangement with exactly two mines is valid.
Input:
rows = 2, cols = 4, n = 3
One possible output:
[
[1, 0, 0, 1],
[0, 1, 0, 0]
]
Explanation: Three mines occupy distinct cells; the remaining cells are empty. The specific positions are random.
0 <= n <= rows * colsrows and cols are positive integers.generate_grid(rows: int, cols: int, n: int) -> list[list[int]].n mines (marked as 1) and rows * cols - n empty cells (marked as 0).