leetcode 130. Surrounded Regions

题目链接:leetcode

思路:
广度优先

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
import collections
class Solution:
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
queue = collections.deque()
for r in range(len(board)):
for c in range(len(board[0])):
if (r in [0, len(board)-1] or c in [0, len(board[0])-1]) and board[r][c] == "O":
queue.append((r, c))
while queue:
#print(queue)
r, c = queue.popleft()
if 0<=r<len(board) and 0<=c<len(board[0]) and board[r][c] == "O":
board[r][c] = "D"
queue.append((r-1, c)); queue.append((r+1, c))
queue.append((r, c-1)); queue.append((r, c+1))
#print(board)
for r in range(len(board)):
for c in range(len(board[0])):
if board[r][c] == "O":
board[r][c] = "X"
elif board[r][c] == "D":
board[r][c] = "O"