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

Flood Fill

LeetCode 733 · ಸುಲಭ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

DFS through cells of the starting colour.

ಸುಲಭArrayDepth-First SearchBreadth-First SearchMatrix
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

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

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

Intuition

Starting from (sr, sc), recolour every cell connected to it that has the original colour. A DFS spreads through same-coloured neighbours.

Approach

  1. 1

    Remember the starting colour.

  2. 2

    DFS: paint the cell, recurse into same-coloured unvisited neighbours.

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

Grid DFSPythonO(m·n) time
class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
        m = len(image)
        n = len(image[0])
        di = [0,+1,0,-1]
        dj = [+1,0,-1,0]
        default_color = image[sr][sc]
        visited = set()
        visited.add((sr,sc))
        def dfs(row,col):
            visited.add((row,col))
            image[row][col]=color
            for k in range(4):
                nrow = row+di[k]
                ncol = col+dj[k]
                if 0<=nrow<m and 0<=ncol<n and image[nrow][ncol]==default_color and (nrow,ncol) not in visited:
                    dfs(nrow,ncol)
        dfs(sr,sc)
        return image

        
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Flood Fill — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Flood Fill ಹಿಂದಿನ intuition ಏನು?

Starting from (sr, sc), recolour every cell connected to it that has the original colour. A DFS spreads through same-coloured neighbours.

Flood Fill (LeetCode 733) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Remember the starting colour. 2. DFS: paint the cell, recurse into same-coloured unvisited neighbours.

Flood Fill ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

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

Flood Fill ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

If the new colour equals the old one, a visited set (or early return) prevents infinite loops.