原题
给定一个二维的矩阵,包含 'X' 和 'O'(字母 O)。
找到所有被 'X' 围绕的区域,并将这些区域里所有的 'O' 用 'X' 填充。
示例:
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 X X X
X O X X
思路
只有和最外层的‘O’不联通的‘O’才会被‘X’替代。使用深度优先标记所有和最外层‘O’联通的‘O’为‘-’,再遍历board将剩余的‘O’改写成‘X’,‘-’改写成‘O’。
代码
class Solution(object):
__row = None
__col = None
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
if not board or not board[0]:
return
self.__row = len(board)
self.__col = len(board[0])
for j in range(self.__row):
self.dfs(board, j, 0)
self.dfs(board, j, self.__col-1)
for i in range(self.__col):
self.dfs(board, 0, i)
self.dfs(board, self.__row-1, i)
for j in range(self.__row):
for i in range(self.__col):
if board[j][i] == 'O':
board[j][i] = 'X'
if board[j][i] == '-':
board[j][i] = 'O'
def dfs(self,board, j, i):
if 0<=i<self.__col and 0<=j<self.__row and board[j][i] == 'O':
board[j][i] = '-'
self.dfs(board,j-1,i)
self.dfs(board,j+1,i)
self.dfs(board,j,i-1)
self.dfs(board,j,i+1)
else:
return