Original title address: https://oj.leetcode.com/problems/surrounded-regions/
Test instructions
Given a 2D board containing ‘X‘
‘O‘
and, capture all regions surrounded by ‘X‘
.
A region was captured by flipping all ‘O‘
s into ‘X‘
s-surrounded region.
For example,
x x x xx o o xx x o xx o x x
After running your function, the board should is:
x x x xx x x xx x x xx O x x
Problem solving ideas: This problem can be solved using BFS and DFS two ways. DFS will time out. BFS can be AC. Start searching from the side, if ' o ', then search for the elements around ' o ' and replace ' o ' with ' D ', so that each side is DFS or BFS again. and the inner ' O ' is not going to change. So down, not surrounded by the ' o ' are all replaced by ' D ', surrounded by ' o ' or ' o ', unchanged. Then iterate over, replace ' o ' with ' X ' and ' D ' into ' o '.
DFS code, because the problem of recursion depth will explode:
classSolution:#@param board, a 9x9 2D array #Capture all regions by modifying the input board In-place. #Don't return any value. defSolve (self, board):defdfs (x, y):ifX<0orX>m-1orY<0orY>n-1orboard[x][y]!='O':returnBoard[x][y]='D'DFS (x-1, y) dfs (x+1, y) dfs (x, y+1) Dfs (x, y-1) ifLen (board) = = 0:returnm= Len (board); n =Len (board[0]) forIinchRange (m): DFS (i, 0); Dfs (i, n-1) forJinchRange (1, n-1): Dfs (0, J); DFS (M-1, J) forIinchRange (m): forJinchrange (n):ifBOARD[I][J] = ='O': board[i][j] = ='X' elifBOARD[I][J] = ='D': board[i][j] = ='O'
BFS Code:
classSolution:#@param board, a 2D array #Capture all regions by modifying the input board In-place. #Don't return any value. defSolve (self, board):#The ' O ' on the outermost four edges of board is certainly not surrounded by ' X ', starting with the ' O ', using BFS to find all the neighboring ' o ', and changing these ' o ' to another symbol, such as ' D '. Then scan the board again and replace ' o ' with ' X ' and ' D ' with ' o '. defFill (x, y):ifX<0orX>m-1orY<0orY>n-1orBoard[x][y]! ='O':returnQueue.append ((x, y)) Board[x][y]='D' defBFS (x, y):ifboard[x][y]=='O': Fill (x, y) whileQueue:curr=queue.pop (0); I=CURR[0]; J=curr[1] Fill (i+1,J); Fill (i-1,j); fill (i,j+1); Fill (i,j-1) ifLen (board) ==0:returnm=len (board); N=len (Board[0]); Queue=[] forIinchrange (N): BFs (0,i); BFS (M-1, i) forJinchRange (1, m-1): BFS (j,0); BFS (J,n-1) forIinchRange (m): forJinchrange (n):ifBOARD[I][J] = ='D': board[i][j] ='O' elifBOARD[I][J] = ='O': board[i][j] ='X'
Reference:
This article references [1] but made a small change. The original BFS function has one more of the following: Queue.append (x, y) is a repetition of the fill function. The result is a double backup for each element of the queue.
[1] http://www.cnblogs.com/zuoyuan/p/3765434.html
[Leetcode] Surrounded regions @ Python