LeetCode 130. Surrounded Regions

题目

Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

Example:

1
2
3
4
X X X X
X O O X
X X O X
X O X X

After running your function, the board should be:

1
2
3
4
X X X X
X X X X
X X X X
X O X X

Explanation:

Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.

思路

BFS.

代码

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
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
row, col = len(board), len(board[0])
q = collections.deque()
for r in range(row):
for c in range(col):
if r in [0, row-1] or c in [0, col-1] and board[r][c] == 'O':
q.append((r, c))
while q:
x, y = q.popleft()
if 0 <= x < row and 0 <= y < col and board[x][y] == 'O':
board[x][y] = 'Y'
for dx, dy in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
q.append((x+dx, y+dy))
for r in range(row):
for c in range(col):
if board[r][c] == 'O':
board[r][c] = 'X'
elif board[r][c] == 'Y':
board[r][c] = 'O'