解法
边上的O一定不会被包围,所以跟它们相连的O也不会被包围
class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
n_row = len(board)
if n_row==0:
return
n_col = len(board[0])
if n_col==0:
return
mark = set()
def dfs(i,j):
mark.add((i,j))
def is_safe(i,j):
return i>=0 and i<n_row and j>=0 and j<n_col
d = [(0,1),(0,-1),(1,0),(-1,0)]
for x,y in d:
ni = i+x
nj = j+y
if is_safe(ni,nj) and board[ni][nj]=='O' and (ni, nj) not in mark:
dfs(ni,nj)
for i in xrange(n_row):
if board[i][0]=='O':
dfs(i,0)
if board[i][-1]=='O':
dfs(i,n_col-1)
for j in xrange(n_col):
if board[0][j]=='O':
dfs(0,j)
if board[n_row-1][j]=='O':
dfs(n_row-1,j)
for i in xrange(1, n_row-1):
for j in xrange(1, n_col-1):
if (i,j) not in mark:
board[i][j] = 'X'