Teaching Kids Programming – Image Flood Fill via DFS and BFS Algorithm


Teaching Kids Programming: Videos on Data Structures and Algorithms

An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535). Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, “flood fill” the image.

flood-fill-image-matrix Teaching Kids Programming - Image Flood Fill via DFS and BFS Algorithm algorithms BFS DFS python teaching kids programming youtube video

To perform a “flood fill”, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.

At the end, return the modified image.

Example 1:
Input:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2

Output: [[2,2,2],[2,2,0],[2,0,1]]

Explanation:

  • From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected.
  • by a path of the same color as the starting pixel are colored with the new color.
  • Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.

Note:

  • The length of image and image[0] will be in the range [1, 50].
  • The given starting pixel will satisfy 0 < = sr < image.length and 0 <= sc < image[0].length.
  • The value of each color in image[i][j] and newColor will be an integer in [0, 65535].

flood-fill-python Teaching Kids Programming - Image Flood Fill via DFS and BFS Algorithm algorithms BFS DFS python teaching kids programming youtube video

We can perform the flood fill in Recursive Depth First Seach Algorithm which is easy to implement but at the risk of a stack overflow especially if the field to fill is large. Alternativly we can implement this using iterative approach in the fashon of either Depth First Search or Breadth First Search.

We can follow the four directions as long as the neighbour pixels are of same color as the starting pixel.

recursive-flood-fill-4 Teaching Kids Programming - Image Flood Fill via DFS and BFS Algorithm algorithms BFS DFS python teaching kids programming youtube video

Recursion Depth First Search Flood Fill Algorithm

Start filling the pixels as long as they have not been seen and also are the same color with the start pixel.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
        R, C = len(image), len(image[0])
        color = image[sr][sc]
        
        seen = set()
        def dfs(r, c):
            if (r, c) in seen:
                return
            seen.add((r, c))                        
            image[r][c] = newColor
            for dr, dc in ((1, 0), (0, 1), (-1, 0), (0, -1)):
                nr = r + dr
                nc = c + dc
                if 0 <= nr < R and 0 <= nc < C and image[nr][nc] == color:
                    dfs(nr, nc)
                    
        dfs(sr, sc)
        return image       
class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
        R, C = len(image), len(image[0])
        color = image[sr][sc]
        
        seen = set()
        def dfs(r, c):
            if (r, c) in seen:
                return
            seen.add((r, c))                        
            image[r][c] = newColor
            for dr, dc in ((1, 0), (0, 1), (-1, 0), (0, -1)):
                nr = r + dr
                nc = c + dc
                if 0 <= nr < R and 0 <= nc < C and image[nr][nc] == color:
                    dfs(nr, nc)
                    
        dfs(sr, sc)
        return image       

As mentioned earlier, this recursive DFS is probably fine in small image but tend to cause stack overflow in practical use.

Iterative Breadth/Depth First Search Flood Fill Algorithm

We can use a queue to implement the Breadth First Search algorithm to flood fill the image.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
        R, C = len(image), len(image[0])
        color = image[sr][sc]
          
        Q = deque([(sr, sc)])
        seen = set()
        while Q:
            r, c = Q.popleft()
            image[r][c] = newColor
            if (r, c) in seen:
                continue
            seen.add((r, c))
            for dr, dc in ((1, 0), (0, 1), (-1, 0), (0, -1)):
                nr = r + dr
                nc = c + dc
                if 0 <= nr < R and 0 <= nc < C and image[nr][nc] == color:
                    Q.append((nr, nc))
        return image
class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
        R, C = len(image), len(image[0])
        color = image[sr][sc]
          
        Q = deque([(sr, sc)])
        seen = set()
        while Q:
            r, c = Q.popleft()
            image[r][c] = newColor
            if (r, c) in seen:
                continue
            seen.add((r, c))
            for dr, dc in ((1, 0), (0, 1), (-1, 0), (0, -1)):
                nr = r + dr
                nc = c + dc
                if 0 <= nr < R and 0 <= nc < C and image[nr][nc] == color:
                    Q.append((nr, nc))
        return image

And here is how the pixels are being filled if we use the queue (Breadth First Search):
floodfill-by-queue Teaching Kids Programming - Image Flood Fill via DFS and BFS Algorithm algorithms BFS DFS python teaching kids programming youtube video

By replacing the queue with the stack – this is similar to Recursion:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
        R, C = len(image), len(image[0])
        color = image[sr][sc]
          
        st = [(sr, sc)]
        seen = set()
        while Q:
            r, c = st.pop(0)
            image[r][c] = newColor
            if (r, c) in seen:
                continue
            seen.add((r, c))
            for dr, dc in ((1, 0), (0, 1), (-1, 0), (0, -1)):
                nr = r + dr
                nc = c + dc
                if 0 <= nr < R and 0 <= nc < C and image[nr][nc] == color:
                    st.append((nr, nc))
        return image
class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
        R, C = len(image), len(image[0])
        color = image[sr][sc]
          
        st = [(sr, sc)]
        seen = set()
        while Q:
            r, c = st.pop(0)
            image[r][c] = newColor
            if (r, c) in seen:
                continue
            seen.add((r, c))
            for dr, dc in ((1, 0), (0, 1), (-1, 0), (0, -1)):
                nr = r + dr
                nc = c + dc
                if 0 <= nr < R and 0 <= nc < C and image[nr][nc] == color:
                    st.append((nr, nc))
        return image

With stack (Depth First Search Algorithm), the image pixels are being filled this way:
floodfill-by-stack Teaching Kids Programming - Image Flood Fill via DFS and BFS Algorithm algorithms BFS DFS python teaching kids programming youtube video

Flood Fill Algorithms

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
1087 words
Last Post: Teaching Kids Programming - Estimating the Performance Speedup (Gain) using Amdahls Law
Next Post: Teaching Kids Programming - The Fisher–Yates Random Shuffle Algorithm in Python

The Permanent URL is: Teaching Kids Programming – Image Flood Fill via DFS and BFS Algorithm

Leave a Reply