Minesweeper LeetCode solution in Python

1
class Solution:
2
def calMines(self, board, x, y):
3
directions = [
4
(-1, -1),
5
(0, -1),
6
(1, -1),
7
(1, 0),
8
(1, 1),
9
(0, 1),
10
(-1, 1),
11
(-1, 0),
12
]
13
mines = 0
14
for d in directions:
15
r, c = x + d[0], y + d[1]
16
if self.isValid(board, r, c) and (board[r][c] == "M" or board[r][c] == "X"):
17
mines += 1
18
return mines
19

20
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
21
x, y = click[0], click[1]
22
options = []
23
if board[x][y] == "M":
24
board[x][y] = "X"
25
else:
26
count = self.calMines(board, x, y)
27
if count == 0:
28
board[x][y] = "B"
29
for r in range(x - 1, x + 2):
30
for c in range(y - 1, y + 2):
31
if self.isValid(board, r, c) and board[r][c] != "B":
32
self.updateBoard(board, [r, c])
33
else:
34
board[x][y] = str(count)
35

36
return board
37

38
def isValid(self, board, a, b):
39
return 0 <= a < len(board) and 0 <= b < len(board[0])

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0