Difficulty: Medium, Asked-In: Amazon, Microsoft, Adobe.
Key takeaway: An excellent problem to learn problem-solving using BFS and DFS.
The flood fill problem is a way to fill a region of connected pixels with a new colour, starting from a given pixel in an image. Here an image is represented by a grid of pixels and each pixel is represented by an integer value.
We are given an image represented by an m x n grid of integers, where image[i][j] represents the pixel value at position (i, j). We are also given the coordinates of a starting pixel (x, y) and a new colour to use for the flood fill operation.
Our goal is to replace the colour of all pixels connected to the starting pixel (x, y) in the four cardinal directions (up, down, left, right) with the new colour, as well as any pixels connected to those pixels, and so on. Once the flood fill algorithm is complete, we need to return the modified image.
One idea is to explore all regions connected to the given colour and paint them with the new colour. To do this, we begin at a starting point (x, y) and paint it with the new colour. We then check the surrounding points (x, y + 1), (x - 1, y), (x + 1, y), and (x, y - 1) to ensure that they are valid and have the same colour as the original. If they do, we paint them with the new colour and repeat this process recursively for surrounding points. This will continue until all connected points of the original colour have been painted with the new colour.
This process continues until all connected points with the original color have been colored with the new color.
floodFillHelper(image, x, y, color, newColor)
m = number of rows in image
n = number of columns in image
if image[x][y] != color
return
image[x][y] = newColor
// Visit each in-bounds neighboring cell
if x > 0
floodFillHelper(image, x - 1, y, color, newColor)
if y > 0
floodFillHelper(image, x, y - 1, color, newColor)
if x + 1 < m
floodFillHelper(image, x + 1, y, color, newColor)
if y + 1 < n
floodFillHelper(image, x, y + 1, color, newColor)
floodFill(image, x, y, newColor)
color = image[x][y]
// Avoid revisiting cells when the color would not change
if color != newColor
floodFillHelper(image, x, y, color, newColor)
return imageTime complexity = O(m*n), where m and n are the dimensions of the image. The worst-case occurs when we need to visit and update every pixel in the image. Space complexity = O(m*n). This is because in the worst case, the recursion stack will maintain a frame for every pixel in the image.
The above idea of flood fill algorithm is tail recursive i.e. the recursive calls are the last instruction. So we can easily implement it iteratively using the stack.
floodFill(image, x, y, newColor)
if image[x][y] == newColor
return image
m = number of rows in image
n = number of columns in image
originalColor = image[x][y]
stack = empty stack
push (x, y) onto stack
while stack is not empty
(i, j) = top element of stack
pop stack
if image[i][j] == originalColor
image[i][j] = newColor
if i + 1 < m
push (i + 1, j) onto stack
if i - 1 >= 0
push (i - 1, j) onto stack
if j + 1 < n
push (i, j + 1) onto stack
if j - 1 >= 0
push (i, j - 1) onto stack
return imageTime complexity = O(mn) in the worst case. Because in the worst case, we need to visit each point in the image at most once. Similarly, space complexity = O(mn) in the worst case, as we need to store all m * n points on the stack in the worst case.
Just like DFS, we can also use the breadth-first search (BFS) to visit points in the image and colour the connected region of points. For this, we initialize a queue to store the points that need to be visited and push the starting point into it. Before starting the loop, we also save the original colour of the starting point in a variable.
Now, we run a loop for BFS traversal where we continuously remove points from the front of the queue and colour them with the new colour. For each point, we also push the four neighbouring points (top, bottom, left, and right) into the queue if they are within the bounds of the image. We continue this process until the queue is empty.
Step 1: First, we check if the starting pixel already has the newColor. If it does, we return the image without making any changes.
Step 2: Now, we create a queue of pairs of integers to store the pixels that need to be visited during the algorithm.
Step 3: We also store the original colour of the starting pixel in the variable orginalColor and define an array of integers called offsets [-1, 0, 1, 0, -1]. We use this array to traverse the image in the four cardinal directions. All surrounding points of point (x, y) are:
Step 4: Now, we run a loop until the queue is empty. At the start of each iteration, we remove the front element of the queue and replace its colour with the newColor. Now we iterate through the offsets[] array and check the four cardinal directions around the current pixel. If the pixel in that direction has the originalColor and is within the bounds of the image, we add it to the queue for processing in future iterations.
Step 5: When the queue is empty, we have visited all reachable pixels with the original colour and we return the modified image.
floodFill(image, x, y, newColor)
if image[x][y] == newColor
return image
m = number of rows in image
n = number of columns in image
originalColor = image[x][y]
queue = empty queue
queue.enqueue (x, y)
offsets = [-1, 0, 1, 0, -1]
while queue is not empty
(row, col) = queue. dequeue()
image[row][col] = newColor
for i from 0 to length(offsets) - 2
nextRow = row + offsets[i]
nextCol = col + offsets[i + 1]
if nextRow and nextCol are within bounds
and image[nextRow][nextCol] == originalColor
queue.enqueue(nextRow, nextCol)
return imageTime complexity = O(mn). Because in the worst case, BFS traversal needs to visit each point in the image at most once. Similarly, space complexity = O(mn), because we need to store all m * n points on the queue in the worst case.
We use the flood fill algorithm in many areas of computer science: image processing, computer graphics, game development, etc.
One of the main advantages of the flood fill algorithm is its simplicity and speed. We can implement it in just a few lines of code, which can quickly fill large areas of an image or game environment. But this algorithm can be affected by memory limits or a large number of connected areas, and performance may become an issue.
Number of Islands: Given a 2D grid of 1s and 0s, where 1 represents land and 0 represents water, count the number of islands in the grid. An island is a group of connected 1s, where a connection is defined as being adjacent horizontally or vertically (not diagonally).
Surrounded Regions: Given a 2D grid of characters, where 'X' represents an obstacle and 'O' represents an open space, identify all the regions that are surrounded by 'X' characters and replace them with 'X'. A region is considered surrounded if it is not connected to any open space on the grid.
Knight's Shortest Path: You are given a chessboard and a starting position for a knight piece. Your task is to find the shortest path for the knight to reach a given destination on the chessboard. The knight moves in an L-shaped pattern, two spaces horizontally and one space vertically, or two spaces vertically and one space horizontally.
Shortest Distance in a Grid with Obstacles: You are given a 2D grid of integers, where some cells contain obstacles and cannot be passed through. Your task is to find the shortest distance between two points in the grid.
Unique Paths: You are given a 2D grid of integers, where 1 represents a block that you cannot pass through and 0 represents an open space that you can pass through. Your task is to count the number of unique paths from the top-left corner to the bottom-right corner of the grid.
Maze: You are given a 2D grid of characters, where 'S' represents the start point, 'E' represents the end point, and '#' represents a wall that you cannot pass through. Your task is to find a path through the maze from the start point to the end point.
Enjoy learning, enjoy coding, enjoy algorithms!