LeetCode130. Surrounded Regions (思路及python解法)

Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

Example:

X X X X
X O O X
X X O X
X O X X

After running your function, the board should be:

X X X X
X X X X
X X X X
X O X X

和连通区域比较类似,不过是和边界为“O”的连通区域。

这道题我用了BFS的算法,主要分三步。

1、把边界为“O”的点放到队列中

2、把队列的连通区域标记出来

3、把没有标记的都设为“X”,把所有标记的都设为“O”。

class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        if not board:return board
        r, c = len(board), len(board[0])
        bfs=[]
        for i in range(r):
            for j in range(c):
                if (i in [0,r-1] or j in [0,c-1]) and board[i][j]=='O':
                    bfs.append([i,j])
        while bfs:
            i, j = bfs.pop(0)
            if 0<=i

 

你可能感兴趣的:(Python,LeetCode)