The problem “733. Flood Fill” requires you to implement the flood fill algorithm, which is a way to repaint a region in an image. Given a 2D image represented as a matrix of integers image, where image[row][col] represents the pixel value at the position (row, col), a starting pixel (sr, sc), and a new color newColor, you’re supposed to “flood fill” the image.
Flood fill means you need to start from the pixel (sr, sc) and replace all the adjacent pixels of the same color with newColor. Adjacent pixels are pixels that share one of the four cardinal directions (up, down, left, right).
Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation: From the starting pixel (1, 1) with pixel value 1, all the adjacent pixels with the same value are replaced by 2.
image is empty or contains only one pixel?newColor is the same as the starting pixel color?(sr, sc) is already newColor, we can return the image as is to avoid unnecessary operations.newColor and recursively apply the same operation to its neighbors.Here’s how we can implement the flood fill algorithm in C++:
class Solution {
public:
void floodFillDFS(vector<vector<int>>& image, int sr, int sc, int oldColor, int newColor) {
// Base case: Check boundaries
if (sr < 0 || sr >= image.size() || sc < 0 || sc >= image[0].size()) {
return;
}
// If the pixel is not the old color, return
if (image[sr][sc] != oldColor) {
return;
}
// Update the color
image[sr][sc] = newColor;
// Recursively call floodFillDFS on all 4 adjacent pixels
floodFillDFS(image, sr + 1, sc, oldColor, newColor);
floodFillDFS(image, sr - 1, sc, oldColor, newColor);
floodFillDFS(image, sr, sc + 1, oldColor, newColor);
floodFillDFS(image, sr, sc - 1, oldColor, newColor);
}
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
if (image.empty() || image[0].empty()) return image;
int oldColor = image[sr][sc];
// If the old color is the same as the new color, don't do anything
if (oldColor == newColor) return image;
floodFillDFS(image, sr, sc, oldColor, newColor);
return image;
}
};
newColor is the same as the existing color at (sr, sc), return the image directly.floodFillDFS:
oldColor.This approach ensures that all connected pixels with the same original color are updated to the newColor efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?