⬅ Previous Topic
Rotten Oranges Problem - BFS in MatrixNext Topic ⮕
Detect Cycle in an Undirected Graph using DFS⬅ Previous Topic
Rotten Oranges Problem - BFS in MatrixNext Topic ⮕
Detect Cycle in an Undirected Graph using DFSTopic Contents
The Flood Fill problem is a classic image processing task. Given a 2D array image
where each element represents the color of a pixel, a starting pixel coordinate (sr, sc)
, and a newColor
, your task is to 'flood fill' the area connected to the starting pixel.
A pixel is considered 'connected' if it has the same color as the starting pixel and is connected 4-directionally (up, down, left, or right).
Replace all such connected pixels with newColor
.
function floodFill(image, sr, sc, newColor) {
const originalColor = image[sr][sc];
if (originalColor === newColor) return image;
const rows = image.length;
const cols = image[0].length;
const queue = [[sr, sc]];
const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
image[sr][sc] = newColor;
while (queue.length > 0) {
const [r, c] = queue.shift();
for (const [dr, dc] of directions) {
const nr = r + dr, nc = c + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && image[nr][nc] === originalColor) {
image[nr][nc] = newColor;
queue.push([nr, nc]);
}
}
}
return image;
}
console.log(floodFill([[1,1,1],[1,1,0],[1,0,1]], 1, 1, 2));
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(1) | If the starting pixel's color is already the new color, the algorithm returns immediately without modifying the image. |
Average Case | O(m × n) | In most practical scenarios, a portion of the image is filled, and the algorithm visits those connected pixels once. |
Worst Case | O(m × n) | If the entire image consists of the same color, the algorithm may visit every pixel, making it linear in the size of the image. |
O(m × n)
Explanation: In the worst case, the stack or queue can hold all pixels of the image if they are all connected and need to be processed.
⬅ Previous Topic
Rotten Oranges Problem - BFS in MatrixNext Topic ⮕
Detect Cycle in an Undirected Graph using DFSYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.