Flood-Fill Algorithm using JavaScript
Last Updated :
03 May, 2024
Given a 2D screen arr[][] where each arr[i][j] is an integer representing the color of that pixel, also given the location of a pixel
(X, Y) and a color C, the task is to replace the color of the given pixel and all the adjacent same-colored pixels with the given color.
Example:
Input:
const grid = [
[1, 1, 0, 0, 0],
[1, 1, 0, 1, 1],
[0, 0, 0, 1, 0],
[0, 0, 1, 1, 0],
[1, 0, 0, 0, 1]
];
Starting point: (0,0)
TargetColor: 2
Output:
2 2 0 0 0
2 2 0 1 1
0 0 0 1 0
0 0 1 1 0
1 0 0 0 1
Explanation:
In the 2D grid, each value indicates the color of a pixel.
The starting point (0,0) indicates the coordinates from where
we begin the flood-fill. We replace all connected pixels
with the target color (2). So, all connected '1's starting
from the starting point are replaced with '2' in the grid.
Using DFS
Using Depth-First Search (DFS), the flood-fill algorithm recursively explores neighboring pixels from a starting point (x, y).
Approach:
- Start at the given starting point (x, y) in the grid.
- Check if the current pixel is within the grid boundaries and has the same color as the starting pixel.
- If the current pixel is valid, replace its color with the target color.
- Recursively explore the neighboring pixels of the current pixel.
- For each neighboring pixel:
- Check if it's within the grid boundaries and has the same color as the starting pixel.
- If valid, apply the replacement color and recursively explore its neighbors.
- Repeat steps 4-5 until all connected pixels with the same color as the starting pixel are replaced with the target color.
Example: Implementation to implement Flood-fill Algorithm using DFS.
JavaScript
function floodFillRecursive(grid, x, y, targetColor, startColor) {
if (x < 0 || x >= grid.length || y < 0
|| y >= grid[0].length ||
grid[x][y] !== startColor) {
return;
}
grid[x][y] = targetColor;
floodFillRecursive(grid, x + 1, y, targetColor, startColor);
floodFillRecursive(grid, x - 1, y, targetColor, startColor);
floodFillRecursive(grid, x, y + 1, targetColor, startColor);
floodFillRecursive(grid, x, y - 1, targetColor, startColor);
}
// Example usage
const grid = [
[1, 1, 0, 0, 0],
[1, 1, 0, 1, 1],
[0, 0, 0, 1, 0],
[0, 0, 1, 1, 0],
[1, 0, 0, 0, 1]
];
const startX = 0;
const startY = 0;
const targetColor = 2;
floodFillRecursive(grid, startX, startY, targetColor, grid[startX][startY]);
console.log("Output Using DFS:");
console.log(grid);
OutputOutput Using DFS:
[
[ 2, 2, 0, 0, 0 ],
[ 2, 2, 0, 1, 1 ],
[ 0, 0, 0, 1, 0 ],
[ 0, 0, 1, 1, 0 ],
[ 1, 0, 0, 0, 1 ]
]
Time complexity: O(m*n)
Space Complexity: O(m+n), due to recursive call stack.
Using BFS
It explores neighboring pixels iteratively from a starting point in the grid.
Approach:
- Initialize a queue (Q).
- Push the starting location of the pixel as given in the input and apply the replacement color to it.
- Iterate over the queue until it's not empty.
- Pop the front node from the queue.
- Check the adjacent pixels of the current pixel.
- If adjacent pixels are valid (within grid boundaries and have the same color as the starting pixel), push them into the queue and apply the replacement color.
- Repeat steps 4-6 until all connected pixels with the same color as the starting pixel are replaced with the target color.
Example: Implementation to implement Flood-fill Algorithm using DFS.
JavaScript
function floodFillIterative(grid, startX, startY, targetColor) {
const startColor = grid[startX][startY];
const queue = [[startX, startY]];
const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]];
while (queue.length > 0) {
const [x, y] = queue.shift();
grid[x][y] = targetColor;
for (const [dx, dy] of directions) {
const newX = x + dx;
const newY = y + dy;
if (newX >= 0 && newX < grid.length
&& newY >= 0 && newY < grid[0].length
&& grid[newX][newY] === startColor) {
queue.push([newX, newY]);
}
}
}
}
// Example usage
const grid = [
[1, 1, 0, 0, 0],
[1, 1, 0, 1, 1],
[0, 0, 0, 1, 0],
[0, 0, 1, 1, 0],
[1, 0, 0, 0, 1]
];
const startX = 2;
const startY = 2;
const targetColor = 2;
floodFillIterative(grid, startX, startY, targetColor);
console.log("Output after BFS approach:");
console.log(grid);
OutputOutput after BFS approach:
[
[ 1, 1, 2, 2, 2 ],
[ 1, 1, 2, 1, 1 ],
[ 2, 2, 2, 1, 0 ],
[ 2, 2, 1, 1, 0 ],
[ 1, 2, 2, 2, 1 ]
]
Time Complexity: O(N*M)
Space Complexity: O(N*M)
Similar Reads
BFS using JavaScript
BFS stands for Breadth First Search is a traversal technique used to traverse a graph. In BFS, we explore the graph level by level, visiting all the neighbors of a node before moving on to its neighbors' neighbors. This means that we prioritize exploring the breadth of the graph rather than its dept
2 min read
Convert Min-Heap into Max-Heap using JavaScript
The objective is to create a max-heap from a given min-heap. To accomplish this, the elements of the array representing the min-heap must be rearranged such that the values of each parent node in the array are greater than or equal to those of its children. Below are the approaches to achieve this w
3 min read
Convert Max-Heap into Min-Heap using JavaScript
Given an array representing a max-heap, the problem is to convert this array into a min-heap using JavaScript. Below are the approaches to convert the max-heap to min-heap using JavaScript: Table of Content Naive MethodIn-Place ConversionNaive MethodA common approach is to take the elements out of t
3 min read
Sum of all subsets in array using JavaScript
We are given an array, we have to print the sum of the subset generated. If the number of elements in the array is n, then 2n subset will be generated. One empty subset will also be generated. So the total subset generated is (2n + 1). Example: Input: 1 , 2, 3 Output: 0 , 1 , 2 , 3 , 3 , 4 , 5 , 6Ex
3 min read
Alternative Sorting of an Array using JavaScript
Alternative sorting means we have to arrange the elements of an array in such a way that the first element is the first maximum and the second element is the first minimum, the third element is the second maximum, the fourth element is the second minimum, and so on. Example: Input: array = [5, 6, 2,
3 min read
Largest Square Formed in a Matrix using JavaScript
Given a matrix, our task is to find the largest square formed in a matrix using JavaScript. The largest square is a square that contains the same number of rows and columns and no more squares can be possible to form in that matrix that contains more rows and columns than this square. The below meth
3 min read
Fractional Knapsack Problem using JavaScript
In the fraction knapsack problem, we are given a set of items, each with a weight and a value, and a knapsack with a maximum weight capacity. We have to put items such that we can gain maximum profit i.e. put a most valuable combination of items in knapsack without exceeding the maximum weight capac
3 min read
First Element to Occur K Times using JavaScript
Given an array and number, our task is to find the first element that occurs exactly k times in an array using JavaScript. Example: Input: array= [1, 2, 3, 4, 2, 5, 6, 4, 2] and k = 3.Output: 2Explanation: Here the first element that occurred 3 times in the array is 2Table of Content Using nested fo
3 min read
Find the Repeating & Missing Numbers in JavaScript Array ?
JavaScript allows us to find the repeating and missing number in a given array which includes numbers from 1 to N range. We are given an array that has numbers present from 1 to N range, where N is any natural number. One number is present two times and one number is missing from the range. We have
3 min read
JavaScript Program to Find Top k Elements
Given an array, our task is to find the top k elements in an unsorted array of integers in JavaScript, either the largest or the smallest. Duplicate values may be in the array. The output will be a new array with the top k elements arranged in a non-ascending order (from largest to smallest). Table
4 min read