Given a 2D board containing'X'and'O'(theletterO), capture all regions surrounded by'X'.
A region is captured by flipping all'O's into'X's in that surrounded region.
For 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
反向思索最简单:哪些‘O’是应该保留的?
从上下左右四个边界往里走,凡是能碰到的
‘O’ ,都是跟边界接壤的,应该保留。
思路:
对于每一个边界上的‘O’作为起点,做若干次广度
优先搜索,对于碰到的‘O’,标记为其他某字符Y;
最后遍历一遍整个地图,把所有的Y恢复成‘O’,把
所有现有的‘O’都改成‘X’
import Queue
class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
def fill(x, y):
if x < 0 or x > height-1 or y < 0 or y > width-1 or board[x][y] != "O":
return
MyQueue.put((x, y))
board[x][y] = "D"
def bfs(x, y):
if board[x][y] == "O":
fill(x, y)
while not MyQueue.empty():
current = MyQueue.get()
i, j = current[0], current[1]
fill(i+1, j)
fill(i-1, j)
fill(i, j+1)
fill(i, j-1)
if len(board) == 0:
return
height, width, MyQueue = len(board), len(board[0]), Queue.Queue()
for i in range(width):
bfs(0, i)
bfs(height - 1, i)
for j in range(1, height - 1):
bfs(j, 0)
bfs(j, width - 1)
for i in range(height):
for j in range(width):
if board[i][j] == "D":
board[i][j] = "O"
elif board[i][j] == "O":
board[i][j] = "X"参考:https://www.jianshu.com/p/3ea288ffdb68