[LeetCode 6.17] Surrounded Regions

Surrounded Regions

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

Explanation:

Surrounded regions shouldn’t be on the border, which means that any ‘O’ on the border of the board are not flipped to ‘X’. Any ‘O’ that is not on the border and it is not connected to an ‘O’ on the border will be flipped to ‘X’. Two cells are connected if they are adjacent cells connected horizontally or vertically.

Python3 Solution:

遍历四边形的边界,如果为“O”,对其进行深度搜索,将遍历到且为“O”的位置标记为‘1’,其它均为‘0’。最后‘1‘即对应“O”,'0’的位置都对应“X”.

class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        if not board or not board[0]:
            return
        row, col = len(board), len(board[0])
        visited = [[0]*col for _ in range(row)]

        def dfs(n, m):
            if n > 0 and board[n-1][m] == 'O' and visited[n-1][m] == 0:
                visited[n-1][m] = 1
                dfs(n-1, m)
            if n+1 < row and board[n+1][m] == 'O' and visited[n+1][m] == 0:
                visited[n+1][m] = 1
                dfs(n+1, m)
            if m > 0 and board[n][m-1] == 'O' and visited[n][m-1] == 0:
                visited[n][m-1] = 1
                dfs(n, m-1)
            if m+1 < col and board[n][m+1] == 'O' and visited[n][m+1] == 0:
                visited[n][m+1] = 1
                dfs(n, m+1)

        for i in range(col):
            if board[0][i] == 'O' and visited[0][i] == 0:
                visited[0][i] = 1
                dfs(0, i)
            if board[row-1][i] == 'O' and visited[row-1][i] == 0:
                visited[row-1][i] = 1
                dfs(row-1, i)
        for j in range(1, row-1):
            if board[j][0] == 'O' and visited[j][0] == 0:
                visited[j][0] = 1
                dfs(j, 0)
            if board[j][col-1] == 'O' and visited[j][col-1] == 0:
                visited[j][col-1] = 1
                dfs(j, col-1)

        for i in range(row):
            for j in range(col):
                if visited[i][j] == 1:
                    board[i][j] = "O"
                elif visited[i][j] == 0:
                    board[i][j] = "X"

你可能感兴趣的:(LeetCode每日一题)