Flood Fill
Implement a flood fill algorithm on a given 2D grid, starting from a specified position , to replace all connected pixels with the same original value with a new value. The connection between pixels is defined by 4-connectivity, where two pixels are considered connected if they are adjacent horizontally or vertically.
The flood fill operation is a fundamental concept in image segmentation, which is crucial in computer vision for separating objects or regions of interest from the rest of the image. This process can be viewed as a graph traversal problem, where each pixel represents a node, and the connections between them are edges. The goal is to traverse the graph, starting from a given node, and update all connected nodes that share the same original value.
Here are the steps to achieve this:
- Identify the starting position and the new value.
- Determine the original value of the starting pixel.
- Check if the starting pixel already has the new value.
- Traverse the grid, updating all connected pixels with the same original value.
This technique is widely used in image editing software.
Example
grid = [[1, 1, 1], [1, 1, 0], [1, 0, 1]] sr = 1, sc = 1, new_val = 2
[[2, 2, 2], [2, 2, 0], [2, 0, 1]]
- Inputs:
gridis a image of integer pixel values, is the seed pixel (0-indexed row and column), andnew_valis the paint colour. - The seed holds the value , so the region to repaint is every reachable from by steps with (up, down, left, right only).
- From the direct neighbours , are ; and are , so they block. From we reach and , and from we reach . All 6 become .
- Pixel is also , but its only neighbours and are . A diagonal touch does not count, so it stays
1. - Output:
[[2, 2, 2], [2, 2, 0], [2, 0, 1]], same shape as the input. Notice that a pixel's value alone is not enough: it must be connected to the seed. Ifnew_valalready equalled , nothing would change.
Constraints
- grid is a 2D list of integers
- (sr, sc) is a valid position in the grid
- new_val is an integer
- Use 4-connectivity (up, down, left, right)
- Return the modified grid