其他分享
首页 > 其他分享> > LeetCode130 被围绕的区域(dfs)

LeetCode130 被围绕的区域(dfs)

作者:互联网

LeetCode130 被围绕的区域

class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        m, n = len(board), len(board[0])
        to_dir = [(1, 0), (-1, 0), (0, 1), (0, -1)]

        def dfs(i, j):

            if i < 0 or i >= m or j < 0 or j >= n or board[i][j] == 'X' or board[i][j] == '#': return
            if board[i][j] == 'O': board[i][j] = '#'
            
            for dx, dy in to_dir:
                dfs(i + dx, j + dy)
        
        for i in range(m):
            dfs(i, 0)
            dfs(i, n - 1)
        for i in range(n):
            dfs(0, i)
            dfs(m - 1, i)
        
        for i in range(m):
            for j in range(n):
                if board[i][j] == 'O': board[i][j] = 'X'
                elif board[i][j] == '#': board[i][j] = 'O'

标签:return,围绕,List,dfs,LeetCode130,range,board
来源: https://www.cnblogs.com/solvit/p/16575670.html