Leetcode 529 Solution

This article provides solution to leetcode question 529 (minesweeper)

https://leetcode.com/problems/minesweeper

Solution

class Solution: def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]: def within_board(board, i, j): m = len(board) n = len(board[0]) return 0 <= i < m and 0 <= j < n
i, j = click if board[i][j] == 'M': board[i][j] = 'X' return board
q = collections.deque() q.append((i, j)) seen = {(i, j)}
while q: i, j = q.popleft()
nei_cnt = 0 nei_cnt += 1 if within_board(board, i - 1, j) and board[i - 1][j] == 'M' else 0 nei_cnt += 1 if within_board(board, i - 1, j - 1) and board[i - 1][j - 1] == 'M' else 0 nei_cnt += 1 if within_board(board, i - 1, j + 1) and board[i - 1][j + 1] == 'M' else 0 nei_cnt += 1 if within_board(board, i, j - 1) and board[i][j - 1] == 'M' else 0 nei_cnt += 1 if within_board(board, i, j + 1) and board[i][j + 1] == 'M' else 0 nei_cnt += 1 if within_board(board, i + 1, j - 1) and board[i + 1][j - 1] == 'M' else 0 nei_cnt += 1 if within_board(board, i + 1, j) and board[i + 1][j] == 'M' else 0 nei_cnt += 1 if within_board(board, i + 1, j + 1) and board[i + 1][j + 1] == 'M' else 0 board[i][j] = 'B' if nei_cnt == 0 else str(nei_cnt)
if nei_cnt == 0: if within_board(board, i - 1, j) and (i - 1, j) not in seen and board[i - 1][j] == 'E': q.append((i - 1, j)) seen.add((i - 1, j)) if within_board(board, i - 1, j - 1) and (i - 1, j - 1) not in seen and board[i - 1][j - 1] == 'E': q.append((i - 1, j - 1)) seen.add((i - 1, j - 1)) if within_board(board, i - 1, j + 1) and (i - 1, j + 1) not in seen and board[i - 1][j + 1] == 'E': q.append((i - 1, j + 1)) seen.add((i - 1, j + 1)) if within_board(board, i, j - 1) and (i, j - 1) not in seen and board[i][j - 1] == 'E': q.append((i, j - 1)) seen.add((i, j - 1)) if within_board(board, i, j + 1) and (i, j + 1) not in seen and board[i][j + 1] == 'E': q.append((i, j + 1)) seen.add((i, j + 1)) if within_board(board, i + 1, j - 1) and (i + 1, j - 1) not in seen and board[i + 1][j - 1] == 'E': q.append((i + 1, j - 1)) seen.add((i + 1, j - 1)) if within_board(board, i + 1, j) and (i + 1, j) not in seen and board[i + 1][j] == 'E': q.append((i + 1, j)) seen.add((i + 1, j)) if within_board(board, i + 1, j + 1) and (i + 1, j + 1) not in seen and board[i + 1][j + 1] == 'E': q.append((i + 1, j + 1)) seen.add((i + 1, j + 1))
return board