# LeetCode-130.被围绕的区域(Surrounded Regions)

## 130. 被围绕的区域

``````输入：board = [["X","X","X","X"],
["X","O","O","X"],
["X","X","O","X"],
["X","O","X","X"]]

["X","X","X","X"],
["X","X","X","X"],
["X","O","X","X"]]

``````

m == board.length n == board[i].length 1 <= m, n <= 200 board[i][j] 为 ‘X’ 或 ‘O’

## 宽度优先搜索

O(N)

``````from collections import deque
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
visited = set()
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == 'X' or (i, j) in visited:
continue

self.helper(i, j, board, visited)

def helper(self, i : int, j : int, board: List[List[str]], visited: set):

directions = [-1, 0, 1, 0, -1] # x, y合一方向数组
start = (i, j)
queue = deque([start])
captured = True
booty = [start]

while len(queue) > 0:
x, y = queue.popleft()

for k in range(4):
neighbor = (x + directions[k], y + directions[k + 1])
if 0 <= neighbor[0] < len(board) and 0 <= neighbor[1] < len(board[i]):
if neighbor not in visited:
if board[neighbor[0]][neighbor[1]] == 'O':
queue.append(neighbor)
booty.append(neighbor)
else:
captured = False

if captured:
for x, y in booty:
board[x][y] = 'X'
``````

``````from collections import deque
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
visited = set()

for i in range(len(board)):
self.bfs(board, visited, i, 0) # 第一列
self.bfs(board, visited, i, len(board[i]) - 1) # 最后一列

for j in range(1, len(board[0]) - 1):
self.bfs(board, visited, 0, j) # 第一行
self.bfs(board, visited, len(board) - 1, j) # 最后一行

for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == 'O' and (i, j) not in visited:
board[i][j] = 'X'

def bfs(self, board, visited, i, j):

if board[i][j] == 'X' or (i, j) in visited:
return

directions = [-1, 0, 1, 0, -1]
queue = deque([(i, j)])

while(len(queue) > 0):
x, y = queue.popleft()

for k in range(4):
neighbor = (x + directions[k], y + directions[k + 1])

if 0 <= neighbor[0] < len(board) and 0 <= neighbor[1] < len(board[i]) and neighbor not in visited and board[neighbor[0]][neighbor[1]] == 'O':
queue.append(neighbor)
``````

–End–