Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 733 · Graph Fundamentals / DFS

Flood Fill

LeetCode 733 · सोपा · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

DFS through cells of the starting colour.

सोपाArrayDepth-First SearchBreadth-First SearchMatrix

मी 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.