LeetCode 733
2020.8.16
美好的一天从一道会做的每日一题开始。
我的通过代码
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
int old = image[sr][sc];
if(old==newColor) return image;
doo(image,sr,sc,newColor,old);
return image;
}
void doo(int[][] image, int sr, int sc, int newColor, int old) {
image[sr][sc] = newColor;
if(sr-1>=0&&sr-1<image.length&&image[sr-1][sc]==old) doo(image,sr-1,sc,newColor,old);
if(sr+1>=0&&sr+1<image.length&&image[sr+1][sc]==old) doo(image,sr+1,sc,newColor,old);
if(sc-1>=0&&sc-1<image[0].length&&image[sr][sc-1]==old) doo(image,sr,sc-1,newColor,old);
if(sc+1>=0&&sc+1<image[0].length&&image[sr][sc+1]==old) doo(image,sr,sc+1,newColor,old);
}
}
还是比较暴力的,不过有用。
途中遇到了一个问题,是对于下面这样一个输入产生的:
[[0,0,0],[0,1,1]]
1
1
1
我实在没想到渲染的颜色会和本来一样,但还是不得不防,毕竟用户会输入什么谁也想不出来。
对于这样一个输入,我的方法函数报了StackOverflowError,就是栈溢出了,原因是那两个1之间疯狂调用对方,就是doo方法里最后两行,展开了一个令人发指的套娃操作。
本来我想着给方法加个方向的,来的方向不再回去。但这也只能是保证相邻的节点不会来回套娃,但它要是绕一圈套娃还是解决不了,比如说对于这样的输入:
[[1,1,1],[1,1,1],[1,1,1]]
1
1
1
加了方向可能能解决相邻的,但是你耐不住它绕一圈套回去啊。。。
后来我发现,这题的目的就是要把和给定点能连通的且值相同的点变为给定值,可如果给定值都和它本身一样了,那那些连通的点自然也一样呀,那不就啥也不用做了吗。
嘿嘿。
int old = image[sr][sc];
if(old==newColor) return image;