[Geeks for Geeks] Flood fill Algorithm

Flood fill Algorithm

An image is represented by a 2-D array of integers, each integer representing the pixel value of the image.

Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, “flood fill” the image.

To perform a “flood fill”, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.

  • Time : O(nm)
  • Space : O(nm)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
void ff(vector<vector<int>>& image, int y, int x, int from, int& to) {
if(0 <= y and y < image.size() and 0 <= x and x < image[0].size() and image[y][x] == from) {
image[y][x] = true;
ff(image, y + 1, x, from, to);
ff(image, y - 1, x, from, to);
ff(image, y, x + 1, from, to);
ff(image, y, x - 1, from, to);
}
}
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
if(image[sr][sc] != newColor)
ff(image, sr, sc, image[sr][sc], newColor);
return image;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/17/PS/GeeksforGeeks/flood-fill-algorithm/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.