思路:主要就是深度搜索,往一点的上下左右四个方法搜,若超出范围或者颜色与旧值不一致直接返回,否则给当前点上新值。
class Solution {
vector<vector<int>> Draw(vector<vector<int>>& image, int sr, int sc, int newColor,int oldColor)
{
if(sr<0||sc<0||sr>=image.size()||sc>=image[0].size()||image[sr][sc]!=oldColor)//若此点超出布局范围或者与原先的颜色不同,直接返回
return image;
image[sr][sc]=newColor;
Draw(image,sr,sc-1,newColor,oldColor);//往左搜索
Draw(image,sr,sc+1,newColor,oldColor);//往右搜索
Draw(image,sr-1,sc,newColor,oldColor);//往上搜索
Draw(image,sr+1,sc,newColor,oldColor);//往下搜索
return image;
}
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
if(newColor==image[sr][sc])
return image;
return Draw(image,sr,sc,newColor,image[sr][sc]);
}
};
做这一题时Draw函数的形参我一开始打算设置oldColor为引用,然后发现结果与我预想的结果不一致,后来才发现,当目标点改为新值之后oldColor也会变为新值,这样找的点的要求就出现了偏差,所以对于传引用还是值需要思虑清楚。值一直不变只做比较的时候可以传引用,但如果值在中途会变但你并不希望它变化则传值。