Flood Fill Algorithm
Ninja has found his new passion for photography. He has clicked some really good photos but in one of his images, he doesn’t like the color of a particular region. So, he decides to change the color of that region. Can you help him with this task?
The image is represented in the form of a 2D array of size M * N. Each pixel in the image is a positive integer. Ninja has given you the coordinates (row and column) of a certain pixel and the new color value. You need to replace the color of the given pixel and all adjacent same-colored pixels with the new color.
Note:
Two pixels are adjacent if they are connected to each other in any of the four directions: up, down, left, or right.
Diagonal pixels are not considered adjacent.
Example:
Consider the image of size 4*4, shown below (left). Let the coordinates of the starting pixel are (1, 2) and the new color is 8. The starting pixel, highlighted with red color, has a pixel value of 3.
On replacing the given pixel and all adjacent same-colored pixels with the new color we get the new image, shown below (right). The modified pixels are highlighted with green color.
Input Format:
The first line of input contains an integer ‘T’ representing the number of test cases.
The first line of every test case contains two space-separated integers ‘M’ and ‘N’ representing the number of rows and columns in the image.
Each of the next ‘M’ lines contains ‘N’ space-separated integers denoting the pixel values of the image.
The next line contains three space-separated integers ‘X’, ‘Y’, and ‘C’ denoting the row and column of the starting pixel and the new color, respectively.
Output Format:
For each test case, the newly colored image is printed in the form of an M * N Matrix.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 100
1 <= M, N <= 50
0 <= X < M
0 <= Y < N
1 <= Image[i][j], C <= 10^5
Time Limit: 1 sec
CodingNinjas
author
3y
Using Recursion
- Starting from the given pixel let's traverse the image using recursion.
- The idea is to replace the colour of the starting pixel with the new colour and repeat the same procedure for the ...read more
CodingNinjas
author
3y
Using BFS
This approach is similar to the previous one but instead of using recursion/DFS, we use BFS to traverse the image.
Algorithm:
- Create an empty queue that can hold coordinates of the pixel.
- Init...read more
Help your peers!
Add answer anonymously...
Top Bajaj Finserv Software Developer interview questions & answers
Popular interview questions of Software Developer
Top HR questions asked in Bajaj Finserv Software Developer
>
Bajaj Finserv Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app