Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 130 · Graph Fundamentals / DFS

Surrounded Regions

LeetCode 130 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Mark border-connected O's, flip the rest.

ಮಧ್ಯಮArrayDepth-First SearchBreadth-First SearchUnion-FindMatrix
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Surrounded Regions (LeetCode 130) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Graph Fundamentals / DFS ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

An 'O' survives only if it's connected to the border. Flood from every border 'O' to mark the safe ones; every unmarked 'O' is surrounded and flips to 'X'.

Approach

  1. 1

    DFS from each 'O' on the four borders.

  2. 2

    Mark visited cells.

  3. 3

    Flip every unvisited 'O' to 'X'.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Border DFSPythonO(m·n) time
class Solution:
    def solve(self, board: list[list[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        m = len(board)
        n = len(board[0])
        visited = [[False]*n for _ in range(m)]
        di = [0,+1,0,-1]
        dj = [+1,0,-1,0]
        def dfs(row,col):
            visited[row][col]=True
            for k in range(4):
                nrow = row+di[k]
                ncol = col+dj[k]
                if 0<=nrow<m and 0<=ncol<n and visited[nrow][ncol]==False and board[nrow][ncol]=="O":
                    dfs(nrow,ncol)

        for j in range(n):
            #first row
            if board[0][j]=="O":
                dfs(0,j)
            #last row
            if board[m-1][j]=="O":
                dfs(m-1,j)
        for i in range(m):
            #first column
            if board[i][0]=="O":
                dfs(i,0)
            #last column
            if board[i][n-1]=="O":
                dfs(i,n-1)
        for row in range(m):
            for col in range(n):
                if visited[row][col]==False and board[row][col]=="O":
                    board[row][col]="X"                    
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Surrounded Regions — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Surrounded Regions ಹಿಂದಿನ intuition ಏನು?

An 'O' survives only if it's connected to the border. Flood from every border 'O' to mark the safe ones; every unmarked 'O' is surrounded and flips to 'X'.

Surrounded Regions (LeetCode 130) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. DFS from each 'O' on the four borders. 2. Mark visited cells. 3. Flip every unvisited 'O' to 'X'.

Surrounded Regions ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(m · n). Space: O(m · n). (Accepted approach: Border DFS.)

Surrounded Regions ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Searching from interior O's is much harder — start from the border.