[LeetCode] Flood Fill

733. Flood Fill

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 newColor. 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 newColor.

Return the modified image after performing the flood fill.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
if(image[sr][sc] == newColor) return image;
queue<pair<int, int>> q;
int targetColor = image[sr][sc], n = image.size(), m = image[0].size();
int dx[4] = {0,1,0,-1}, dy[4] = {-1,0,1,0};
q.push({sr,sc});
image[sr][sc] = newColor;
while(!q.empty()) {
auto [y, x] = q.front(); q.pop();
for(int i = 0; i < 4; i++) {
int ny = y + dy[i], nx = x + dx[i];
if(0 <= nx and nx < m and 0 <= ny and ny < n and image[ny][nx] == targetColor) {
image[ny][nx] = newColor;
q.push({ny,nx});
}
}
}
return image;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/15/PS/LeetCode/flood-fill/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.