原题
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:
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
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. 首先找出在边界的O, 将它们加到队列中, 然后对它们进行BFS搜索, 将它和它相邻的O转化为D. 棋盘里剩下的O则是被X包围住的O, 遍历棋盘, 将O改为X, 将D还原为O.
Time: O(n)
Space: O(n)
代码
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()
# get the index of all O on the boarder
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))
# bfs, make the adjacent O into D
while q:
x, y = q.popleft()
if 0 <= x < row and 0 <= y < col and board[x][y] == 'O':
board[x][y] = 'D'
for dx, dy in [(-1,0),(1,0),(0,-1),(0,1)]:
q.append((x+dx, y+dy))
# make the rest of O into X and make the D into 0
for r in range(row):
for c in range(col):
if board[r][c] == 'O':
board[r][c] = 'X'
elif board[r][c] == 'D':
board[r][c] = 'O'
本文介绍了一种使用BFS算法解决二维棋盘上O型字符被X型字符围困的问题。通过先标记边界上的O并进行搜索,再将未被触及的O转化为X,实现了对被围困区域的有效捕获。
538

被折叠的 条评论
为什么被折叠?



