python leetcode 130. Surrounded Regions
阿新 • • 發佈:2018-12-14
注意遍歷的順序,從四周開始。與Pacific Atlantic Water Flow類似。
class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
visit=set()
change=set()
m=len(board)
if m==0: return
n=len(board[0])
def dfs(board,x,y,visit):
visit.add((x,y))
res={(x,y)}
for dx,dy in zip((-1,0,1,0),(0,-1,0,1)):
nx,ny=x+dx,y+dy
if nx<0 or nx>=len(board) or ny<0 or ny>=len(board[0]) or board[ nx][ny]=='X' or (nx,ny) in visit:
continue
res=res| dfs(board,nx,ny,visit)
return res
for i in range(m):
if board[i][0] == 'O' and (i,0) not in visit:
change=change|dfs(board,i,0,visit)
for i in range(m):
if board[i][n-1] == 'O' and (i,n-1) not in visit:
change=change|dfs(board,i,n-1,visit)
for j in range(1,n-1):
if board[0][j]=='O' and (0,j) not in visit:
change=change|dfs(board,0,j,visit)
for j in range(1,n-1):
if board[m-1][j]=='O' and (m-1,j) not in visit:
change=change|dfs(board,m-1,j,visit)
for i in range(m):
for j in range(n):
if board[i][j]=='X' or (i,j) in change:
continue
board[i][j]='X'