An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).
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.
At the end, return the modified image.
这题很简单,常见的深度优先搜索很适合。但我一开始提交的时候有些测试用例并不对,原因是newcolor 和原始像素值一致。深度优先一个很重要的问题就是访问过的数据需要被有效标记,避免二次访问,当newcolor跟原始数据一致的时候,改变原始数据并不能产生想要的标记效果,导致无法跳出递归的循环。
代码:
class Solution {
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
vector<vector<int>> res(image);
helper(res, sr, sc, newColor);
return res;
}
void helper(vector<vector<int>>& res, int sr, int sc, int newColor) {
int oriColor = res[sr][sc];
res[sr][sc] = newColor;
int nrow = res.size();
if (nrow < 1) return;
int ncol = res[0].size();
if (sr - 1 >= 0 && res[sr - 1][sc] == oriColor && res[sr - 1][sc] != newColor) {
helper(res, sr - 1, sc, newColor);
}
if (sr + 1 < nrow && res[sr + 1][sc] == oriColor && res[sr + 1][sc] != newColor) {
helper(res, sr + 1, sc, newColor);
}
if (sc - 1 >= 0 && res[sr][sc - 1] == oriColor && res[sr][sc - 1] != newColor) {
helper(res, sr, sc - 1, newColor);
}
if (sc + 1 < ncol && res[sr][sc + 1] == oriColor && res[sr][sc + 1] != newColor) {
helper(res, sr, sc + 1, newColor);
}
return;
}
};