Skip to the content.

leetcode [130] 被围绕的区域


Contact me:

Blog -> https://cugtyt.github.io/blog/index
Email -> cugtyt@qq.com
GitHub -> Cugtyt@GitHub


给定一个二维的矩阵,包含 ‘X’ 和 ‘O’(字母 O)。

找到所有被 ‘X’ 围绕的区域,并将这些区域里所有的 ‘O’ 用 ‘X’ 填充。

示例:

X X X X
X O O X
X X O X
X O X X
运行你的函数后,矩阵变为:

X X X X
X X X X
X X X X
X O X X
解释:

被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上,或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。
class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        if len(board) == 0 or len(board[0]) == 0:
            return
        visited = [[False] * len(board[0]) for _ in range(len(board))]
        for i in range(len(board)):
            if board[i][0] == 'O' and not visited[i][0]:
                self.visit(board, visited, i, 0)
            if board[i][-1] == 'O' and not visited[i][-1]:
                self.visit(board, visited, i, len(board[0]) - 1)
        for i in range(len(board[0])):
            if board[0][i] == 'O' and not visited[0][i]:
                self.visit(board, visited, 0, i)
            if board[-1][i] == 'O' and not visited[-1][i]:
                self.visit(board, visited, len(board) - 1, i)
        for i in range(1, len(board) - 1):
            for j in range(1, len(board[0]) - 1):
                if board[i][j] == 'O' and not visited[i][j]:
                    board[i][j] ='X'


    def visit(self, board, visited, i, j):
        visited[i][j] = True
        dirs = [[i - 1, j], [i + 1, j], [i, j - 1], [i, j + 1]]
        for x, y in dirs:
            if 0 <= x < len(board) and 0 <= y < len(board[0]) and board[x][y] == 'O' and not visited[x][y]:
                visited[x][y] = True
                self.visit(board, visited, x, y)