目录

0130:被围绕的区域(★)

力扣第 130 题

题目

给你一个 m x n 的矩阵 board ,由若干字符 'X''O' 组成,捕获 所有 被围绕的区域

  • 连接:一个单元格与水平或垂直方向上相邻的单元格连接。
  • 区域:连接所有 'O' 的单元格来形成一个区域。
  • 围绕:如果您可以用 'X' 单元格 连接这个区域,并且区域中没有任何单元格位于 board 边缘,则该区域被 'X' 单元格围绕。

通过将输入矩阵 board 中的所有 '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"]]

解释:

在上图中,底部的区域没有被捕获,因为它在 board 的边缘并且不能被围绕。

示例 2:

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

输出:[["X"]]

提示:

  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 200
  • board[i][j]'X''O'

相似问题:

分析

  • 只有与边界连通的 ‘O’ 才不会被填充
  • 可以用 dfs 或 bfs 遍历找,更一般的是用并查集
    • 将边界上的 ‘O’ 都与哑节点 m*n 连通
    • 再将相邻的 ‘O’ 连通
    • 最后将不与哑节点连通的 ‘O’ 换成 ‘X’ 即可

解答

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        def find(x):
            if f[x]!=x:
                f[x]=find(f[x])
            return f[x]
        
        def union(x,y):
            f[find(x)]=find(y)

        m,n = len(board),len(board[0])
        f = list(range(m*n+1))
        A = [(i,j) for i in range(m) for j in range(n) if board[i][j]=='O']
        for i,j in A:
            if i in [0,m-1] or j in [0,n-1]:
                union(i*n+j,m*n)
            if i and board[i-1][j]=='O':
                union(i*n+j,(i-1)*n+j)
            if j and board[i][j-1]=='O':
                union(i*n+j,i*n+j-1)
        for i,j in A:
            if find(i*n+j)!=find(m*n):
                board[i][j] = 'X'

73 ms