Total Accepted: 43584 Total Submissions: 284350 Difficulty: Medium
Given a 2D board containing 'X'
and 'O'
, 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了,非递归的BFS和DFS都可以AC(递归的很可能爆栈),找出外面的O并替换为A,剩下的所有的O就是要找的,flip为X即可,再把A替换为O
AC之后的结果来看,DFS所需时间是BFS两倍。
BFS实现:
1 class Solution(object): 2 def solve(self, board): 3 """ 4 :type board: List[List[str]] 5 :rtype: void Do not return anything, modify board in-place instead. 6 """ 7 if board==[]: 8 return 9 width = len(board[0]) 10 height = len(board) 11 edgeNods=[] 12 for column in range(width): #todo: all edgeNode 13 edgeNode = (0, column) 14 if board[0][column]=='O': 15 edgeNods.append(edgeNode) 16 for line in range(height): #todo: all edgeNode 17 edgeNode = (line, 0) 18 if board[line][0]=='O': 19 edgeNods.append(edgeNode) 20 for column in range(width): #todo: all edgeNode 21 edgeNode = (height-1, column) 22 if board[height-1][column]=='O': 23 edgeNods.append(edgeNode) 24 for line in range(height): #todo: all edgeNode 25 edgeNode = (line, width-1) 26 if board[line][width-1]=='O': 27 edgeNods.append(edgeNode) 28 29 stack = edgeNods 30 while stack: 31 nod = stack.pop(0) 32 if board[nod[0]][nod[1]] == 'X' or board[nod[0]][nod[1]] == 'A' : 33 continue 34 else: 35 board[nod[0]][nod[1]] = 'A' 36 37 neighbours=[] 38 neighbours.append((nod[0]-1, nod[1])) 39 neighbours.append((nod[0]+1, nod[1])) 40 neighbours.append((nod[0], nod[1]-1)) 41 neighbours.append((nod[0], nod[1]+1)) 42 for neiber in neighbours: 43 if neiber[0]<0 or neiber[0] >= height \ 44 or neiber[1] <0 or neiber[1] >= width: 45 continue 46 if board[neiber[0]][neiber[1]] == 'X' or board[neiber[0]][neiber[1]] == 'A' : 47 continue 48 if (neiber in stack): 49 continue 50 stack.append(neiber) 51 52 for column in range(width): 53 for line in range(height): 54 if board[line][column] == 'O': 55 board[line][column]= "X" 56 for column in range(width): 57 for line in range(height): 58 if board[line][column] == 'A': 59 board[line][column]='O'