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

Number of Enclaves

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

Flood from the border, count the rest.

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

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

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

Intuition

Land connected to the border can walk off the grid. DFS from every border land cell to mark it; any land left unmarked is enclosed.

Approach

  1. 1

    DFS from every land cell on the four borders.

  2. 2

    Count land cells not visited.

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

Border DFSPythonO(m·n) time
class Solution:
    def numEnclaves(self, board: List[List[int]]) -> int:
        m  = len(board)
        n = len(board[0])
        visited = [[False]*n for _ in range(m)]

        def dfs(i,j):
            visited[i][j]=True
            di = [0,+1,0,-1]
            dj = [+1,0,-1,0]
            for k in range(4):
                nrow = i+di[k]
                ncol = j+dj[k]
                if 0<=nrow<m and 0<=ncol<n and visited[nrow][ncol]==False and board[nrow][ncol]==1:
                    dfs(nrow,ncol)


        for j in range(n):

            #first row
            if board[0][j]==1:
                dfs(0,j)

            #last row
            if board[m-1][j]==1:
                dfs(m-1,j)
            
        for i in range(m):

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

Number of Enclaves — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Number of Enclaves ಹಿಂದಿನ intuition ಏನು?

Land connected to the border can walk off the grid. DFS from every border land cell to mark it; any land left unmarked is enclosed.

Number of Enclaves (LeetCode 1020) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. DFS from every land cell on the four borders. 2. Count land cells not visited.

Number of Enclaves ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

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

Number of Enclaves ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Think in reverse — find what escapes, not what's trapped.