Flood Fill
Problem
An image is represented by an m x n
integer grid image
where image[i][j]
represents the pixel value of the image.
You are also given three integers sr
, sc
, and color
. You should perform a flood fill on the image starting from the pixel image[sr][sc]
.
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), and so on. Replace the color of all of the aforementioned pixels with color
.
Return the modified image after performing the flood fill.
Solution Approach
Expected Time complexity:
Click - to see solution code
- C++
class Solution {
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc,
int color) {
deque<pair<int, int>> q;
int col = image[sr][sc];
int n = image.size();
int m = image[0].size();
q.push_back({sr, sc});
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
while (q.size()) {
auto p = q.front();
q.pop_front();
int i = p.first, j = p.second;
if (image[p.first][p.second] != col) continue;
image[i][j] = -1;
for (int k = 0; k < 4; k++) {
int x = dx[k] + i;
int y = dy[k] + j;
if (x >= 0 && x < n && y >= 0 && y < m && image[x][y] == col)
q.push_back({x, y});
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (image[i][j] == -1) image[i][j] = color;
}
}
return image;
}
};