Skip to content

Commit 4045c92

Browse files
committed
529
1 parent 9f06b6e commit 4045c92

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

DFS/traditionalDFS/529.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
## 529 Minesweeper
2+
3+
#### Description
4+
5+
[link](https://leetcode.com/problems/minesweeper/)
6+
7+
---
8+
9+
#### Solution
10+
11+
**这里讲一下DFS的时间复杂度判断:如果是最坏情况的话,首先因为初始DFS的循环是O(M + N),每个点的最大遍历长度是O(MN),这就是最坏情况的时间复杂度**
12+
13+
---
14+
15+
#### Code
16+
17+
> 最坏情况下是O(n^2)
18+
19+
```python
20+
class Solution:
21+
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
22+
if not board:
23+
return []
24+
25+
m, n = len(board), len(board[0])
26+
i, j = click[0], click[1]
27+
28+
# If a mine ('M') is revealed, then the game is over - change it to 'X'.
29+
if board[i][j] == 'M':
30+
board[i][j] = 'X'
31+
return board
32+
33+
# run dfs to reveal the board
34+
self.dfs(board, i, j)
35+
return board
36+
37+
def dfs(self, board, i, j):
38+
if board[i][j] != 'E':
39+
return
40+
41+
m, n = len(board), len(board[0])
42+
directions = [(-1,-1), (0,-1), (1,-1), (1,0), (1,1), (0,1), (-1,1), (-1,0)]
43+
44+
mine_count = 0
45+
46+
for d in directions:
47+
ni, nj = i + d[0], j + d[1]
48+
if 0 <= ni < m and 0 <= nj < n and board[ni][nj] == 'M':
49+
mine_count += 1
50+
51+
if mine_count == 0:
52+
board[i][j] = 'B'
53+
else:
54+
board[i][j] = str(mine_count)
55+
return
56+
57+
# if not mine_count nor mine, is Blank for spread dfs
58+
for d in directions:
59+
ni, nj = i + d[0], j + d[1]
60+
if 0 <= ni < m and 0 <= nj < n:
61+
self.dfs(board, ni, nj)
62+
```

0 commit comments

Comments
 (0)