You are given a 2D char matrix representing the game board and a list of click positions. The board consists of the following characters:
You are supposed to handle clicks in the following way:
Return the board after processing all the given clicks.
The click positions are given in an array of arrays clicks
, where each element is an array [i, j] that represents the row index and column index of the board where the user clicked.
Suppose the answer is:
def updateBoard(board, clicks):
def count_adjacent_mines(x, y):
mines_count = 0
for dx, dy in [(-1, -1), (-1, 0), (-1, 1),
( 0, -1), ( 0, 1),
( 1, -1), ( 1, 0), ( 1, 1)]:
nx, ny = x + dx, y + dy
if 0 <= nx < len(board) and 0 <= ny < len(board[0]) and board[nx][ny] == 'M':
mines_count += 1
return mines_count
def reveal(x, y):
if board[x][y] != 'E':
return
adjacent_mines = count_adjacent_mines(x, y)
if adjacent_mines > 0:
board[x][y] = str(adjacent_mines)
else:
board[x][y] = 'B'
for dx, dy in [(-1, -1), (-1, 0), (-1, 1),
( 0, -1), ( 0, 1),
( 1, -1), ( 1, 0), ( 1, 1)]:
nx, ny = x + dx, y + dy
if 0 <= nx < len(board) and 0 <= ny < len(board[0]):
reveal(nx, ny)
for click in clicks:
x, y = click
if board[x][y] == 'M':
board[x][y] = 'X'
else:
reveal(x, y)
return board
By following this strategy, we can correctly simulate the Minesweeper game as per the given problem statement and clicks.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?