https://leetcode-cn.com/problems/surrounded-regions/comments/
两次遍历。第一次先遍历边界,dfs将所有与边界O相连的O置为‘-’。之后再遍历所有,将所有O变为X,所有’-‘变为O
class Solution:
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
n = len(board)
if n == 0:
return
m = len(board[0])
#对四条边界上的元素dfs遍历
for i in range(n):
self.dfs(i, 0, n, m, board)
self.dfs(i, m-1, n, m, board)
for j in range(m):
self.dfs(0, j, n, m, board)
self.dfs(n-1, j, n, m, board)
#遍历所有
for i in range(n):
for j in range(m):
#注意先后顺序不能颠倒
if board[i][j] == 'O':
board[i][j] = 'X'
if board[i][j] == '-':
board[i][j] = 'O'
def dfs(self, row, col, rows, cols, board):
if row >= 0 and row < rows and col >= 0 and col < cols and board[row][col] == 'O':
board[row][col] = '-' #特殊标记
#dfs遍历上下左右
self.dfs(row, col-1, rows, cols, board)
self.dfs(row, col+1, rows, cols, board)
self.dfs(row-1, col, rows, cols, board)
self.dfs(row+1, col, rows, cols, board)