Skip to content

Commit 86f2dcb

Browse files
authored
Update 0130.被围绕的区域.md, 增加Python3 版本的DFS解法
增加Python3 版本的DFS解法,在leetcode上测试通过。
1 parent bf51d47 commit 86f2dcb

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

problems/0130.被围绕的区域.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,55 @@ class Solution {
385385
}
386386
}
387387
```
388+
### Python3
389+
390+
```Python
391+
// 深度优先遍历
392+
class Solution:
393+
dir_list = [(0, 1), (0, -1), (1, 0), (-1, 0)]
394+
def solve(self, board: List[List[str]]) -> None:
395+
"""
396+
Do not return anything, modify board in-place instead.
397+
"""
398+
row_size = len(board)
399+
column_size = len(board[0])
400+
visited = [[False] * column_size for _ in range(row_size)]
401+
# 从边缘开始,将边缘相连的O改成A。然后遍历所有,将A改成O,O改成X
402+
# 第一行和最后一行
403+
for i in range(column_size):
404+
if board[0][i] == "O" and not visited[0][i]:
405+
self.dfs(board, 0, i, visited)
406+
if board[row_size-1][i] == "O" and not visited[row_size-1][i]:
407+
self.dfs(board, row_size-1, i, visited)
408+
409+
# 第一列和最后一列
410+
for i in range(1, row_size-1):
411+
if board[i][0] == "O" and not visited[i][0]:
412+
self.dfs(board, i, 0, visited)
413+
if board[i][column_size-1] == "O" and not visited[i][column_size-1]:
414+
self.dfs(board, i, column_size-1, visited)
415+
416+
for i in range(row_size):
417+
for j in range(column_size):
418+
if board[i][j] == "A":
419+
board[i][j] = "O"
420+
elif board[i][j] == "O":
421+
board[i][j] = "X"
422+
423+
424+
def dfs(self, board, x, y, visited):
425+
if visited[x][y] or board[x][y] == "X":
426+
return
427+
visited[x][y] = True
428+
board[x][y] = "A"
429+
for i in range(4):
430+
new_x = x + self.dir_list[i][0]
431+
new_y = y + self.dir_list[i][1]
432+
if new_x >= len(board) or new_y >= len(board[0]) or new_x < 0 or new_y < 0:
433+
continue
434+
self.dfs(board, new_x, new_y, visited)
435+
436+
```
388437

389438
<p align="center">
390439
<a href="https://programmercarl.com/other/kstar.html" target="_blank">

0 commit comments

Comments
 (0)