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.