-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path130.被围绕的区域.py
46 lines (41 loc) · 1.24 KB
/
130.被围绕的区域.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#
# @lc app=leetcode.cn id=130 lang=python
#
# [130] 被围绕的区域
#
# @lc code=start
class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: None Do not return anything, modify board in-place instead.
"""
if not board:
return
self.board = board
m, n = len(board), len(board[0])
self.map = [[False for _ in range(n)] for _ in range(m)]
for i in range(m):
if board[i][0] == 'O':
self.dfs(i,0)
if board[i][n-1] == 'O':
self.dfs(i,n-1)
for j in range(n):
if board[0][j] == 'O':
self.dfs(0,j)
if board[m-1][j] == 'O':
self.dfs(m-1,j)
for i in range(m):
for j in range(n):
if board[i][j] == 'O' and not self.map[i][j]:
board[i][j] = 'X'
return board
def dfs(self,i,j):
if i<0 or i>=len(self.board) or j<0 or j>=len(self.board[0]) or self.board[i][j] != 'O' or self.map[i][j] == True:
return
self.map [i][j] = True
self.dfs(i-1,j)
self.dfs(i+1,j)
self.dfs(i,j-1)
self.dfs(i,j + 1)
# @lc code=end