- Surrounded Regions Medium
1816
663
Add to List
Share Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
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 Explanation:
Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.
思路: 1.边界遍历,找到"O",执行dfs,把相连的"O"都置为"Y" 2.遍历二维数组,把剩下的"O"置为"X" 2.遍历二维数组,把"Y"置为"O"
代码:python3
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not board: return
def dfs(board,r,c):
if board[r][c]=="O":
board[r][c]="Y"
if r>0 and board[r-1][c]=="O":
dfs(board,r-1,c)
if c>0 and board[r][c-1]=="O":
dfs(board,r,c-1)
if r<len(board)-1 and board[r+1][c]=="O":
dfs(board,r+1,c)
if c<len(board[0])-1 and board[r][c+1]=="O":
dfs(board,r,c+1)
for i in range(len(board)):
if board[i][0]=="O":
dfs(board,i,0)
if board[i][len(board[0])-1]=="O":
dfs(board,i,len(board[0])-1)
for j in range(len(board[0])):
if board[0][j]=="O":
dfs(board,0,j)
if board[len(board)-1][j]=="O":
dfs(board,len(board)-1,j)
print(board)
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j]=="O":
board[i][j]="X"
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j]=="Y":
board[i][j]="O"
时间复杂度:O(m^2) 空间复杂度:O(m^2)