给你一个 m x n 的矩阵 board ,由若干字符 ‘X’ 和 ‘O’ ,找到所有被 ‘X’ 围绕的区域,并将这些区域里所有的 ‘O’ 用 ‘X’ 填充。

示例 1:

输入:board = [["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’。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。

示例 2:

输入:board = [["X"]]
输出:[["X"]]

提示:

  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 200
  • board[i][j] 为 ‘X’ 或 ‘O’

Python 解答:
1.DFS

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

        for i in range(m):
            if board[i][0] == 'O':
                lis.append([i, 0])
            if board[i][n-1] == 'O':
                lis.append([i, n-1])
        for j in range(n):
            if board[0][j] == 'O':
                lis.append([0, j])
            if board[m-1][j] == 'O':
                lis.append([m-1, j])

        def dfs(board, item):
            x, y = item[0], item[1]
            board[x][y] = 'S'
            if x+1 < m and board[x+1][y] == 'O':
                dfs(board, [x+1, y])
            if -1 < x-1 and board[x-1][y] == 'O':
                dfs(board, [x-1, y])
            if y+1 < n and board[x][y+1] == 'O':
                dfs(board, [x, y+1])
            if -1 < y-1 and board[x][y-1] == 'O':
                dfs(board, [x, y-1])

        for item in lis:
            dfs(board, item)

        for i in range(m):
            for j in range(n):
                if board[i][j] == 'O':
                    board[i][j] = 'X'
                elif board[i][j] =='S':
                    board[i][j] = 'O'
最后修改日期: 2021年8月11日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。