Leetcode 130. Surrounded region | Python

Time:2020-11-9

130. Surrounded area


Source: leetcode https://leetcode-cn.com/problems/surrounded-regions

subject


Given a two-dimensional matrix, it contains‘X’and‘O’Letter O)。

Find all the‘X’Around the area, and put all of these areas in‘O’use‘X’fill.

Example:

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

After running your function, the matrix changes to:

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

Explanation:

The enclosed interval does not exist on the boundary, in other words, on any boundary‘O’Will not be filled as‘X’。 Anything that is not on the boundary, or not on the boundary‘O’Connected‘O’It’s going to end up being filled with‘X’。 Two elements are said to be “connected” if they are adjacent horizontally or vertically.

Thinking of problem solving


Idea: DFS, BFS

First look at the title, given the two-dimensional matrix, contains‘X’and‘O’Letter O)。 Let’s look at the explanation part, any boundary‘O’Will not be filled as‘X’Now that is to say, there are three parts:

  • Capable of forming an encirclement‘X’
  • cover‘X’Besieged‘O’
  • Not by‘X’Besieged‘O’

Now the requirements of the title will be surrounded‘O’, into‘X’。 As I said before, it’s not surrounded‘O’, is on the boundary, and the side description and boundary‘O’Connected‘O’It won’t be‘X’fill.

Then we can consider the diffusion from the boundary according to this property, and mark the unfilled ones first‘O’That is, with the boundary‘O’The connected parts, then the rest‘O’Will be surrounded and transformed into‘X’。 The specific measures are as follows:

  • With the boundary‘O’As a starting point, mark the letters connected or indirectly to it‘O’
  • When the top part of the‘O’At this point, start to traverse the matrix to judge each letter (Note: the marked part is not to be replaced)

    • If the letter is the marked part, it is converted back to‘O’
    • If the letter is an unmarked department, convert it to‘X’

Note: the title requires in-situ modification. When marking, mark the part connected with boundary ‘o’ (including boundary ‘o’) as’m ‘.

We now use depth first search (DFS) and breadth first search (BFS) to solve this problem. The specific code is as follows.

code implementation


#Depth first search (DFS)
class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        if not board or len(board)==0:
            return

        def dfs(board, i, j):
            #Not in the matrix, or if it is already marked, skip directly
            if not (0<=i<m) or not (0<=j<n) or board[i][j] != 'O':
                return
            
            #When an 'o' is identified as unlabeled and directly or indirectly connected to the boundary 'o', it is marked as'm '
            board[i][j] = 'M'
            #Spread to four directions
            #Up, down, left and right
            dfs(board, i-1, j)
            dfs(board, i+1, j)
            dfs(board, i, j-1)
            dfs(board, i, j+1)
            

        m = len(board)
        n = len(board[0])

        #Search from the 'o' of the boundary
        for i in range(m):
            for j in range(n):
                #First confirm whether I and j are on the boundary
                is_frontier = (i == 0 or j == 0 or i == m-1 or j == n-1)
                if is_frontier and board[i][j] == 'O':
                    dfs(board, i, j)
        
        #Traversing the two-dimensional array, the marked'm 'is converted to' o ', and the unmarked is converted to' x '
        for i in range(m):
            for j in range(n):
                if board[i][j] == 'O':
                    board[i][j] = 'X'
                if board[i][j] == 'M':
                    board[i][j] = 'O'

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

        from collections import deque
        queue = deque()

        #BFS is different from DFS and continues to search in the direction that satisfies the condition
        #All BFS that meet the conditions are queued
        #Join the border 'o' first
        for i in range(m):
            #Here are the leftmost and rightmost columns of a two-dimensional matrix
            if board[i][0] == 'O':
                queue.append((i, 0))
            if board[i][n-1] == 'O':
                queue.append((i, n-1))
        
        for j in range(n):
            #Here are the first and last rows of the two-dimensional matrix
            if board[0][j] == 'O':
                queue.append((0, j))
            if board[m-1][j] == 'O':
                queue.append((m-1, j))
        
        #Now we're out of the team. At present, all of them are boundary o's
        #At the same time of leaving the queue, mark and find the part of the queue connected with the boundary 'o'
        while queue:
            x, y = queue.popleft()
            board[x][y] = 'M'
            #Find connected parts
            for nx, ny in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]:
                if 0 <= nx < m and 0 <= ny < n and board[nx][ny] == 'O':
                    queue.append((nx, ny))
        
        #Similarly, after marking, traverse the entire two-dimensional matrix and transform
        for i in range(m):
            for j in range(n):
                if board[i][j] == 'O':
                    board[i][j] = 'X'
                if board[i][j] == 'M':
                    board[i][j] = 'O'

Achieving results


Leetcode 130. Surrounded region | Python

Leetcode 130. Surrounded region | Python

Welcome to our attention


The official account [book collection]

Recommended Today

The course of using Chinese software of poedit Pro

Poedit pro (formerly known as poedit) is a free (professional version charge), open source and cross platform gettext class (. Po format, gettext is used in the application program for program internationalization) International Translation editor. It is also one of the most widely used software of the same type. At present, it is available in […]