目录
1.每日一句
我的宇宙为你藏着无数个星球
2.作者简介
🏡个人主页:XiaoXiaoChen-2716
📚学习专栏:力扣专栏
🕒发布日期:2022/11/15
『LeetCode|每日一题』颜色填充
1.每日一题
2.解题思路
2.1 思路分析(DFS)
S1:首先根据题意,我们知道改变的颜色题目给出来了,所以我们还需要定义一个原来的颜色oldColor作为dfs函数的参数,至于其它的参数,无非就是方向参数,矩阵还有两个颜色参数;
S2:刚开始需要做越界检查,也就是限定i、j的范围;
S3:然后就是排除不能继续遍历的情况,首先就是当前位置的颜色不等于原来的老颜色,然后就是当前这个位置已经涂上了新颜色,这两种情况也要直接返回;
S4:没遍历一个符合要求的点也要记得把该点涂上新颜色;
S5:在传入参数时,老颜色就是题目给的位置的点的颜色,也就是image[sr][sc]
2.2 核心代码
private void dfs(int[][] image, int i, int j, int newColor , int oldColor){
int row = image.length;
int col = image[0].length;
if(i < 0 || i >= row || j < 0 || j >= col || image[i][j] != oldColor || image[i][j] == newColor){
return ;
}
image[i][j] = newColor;
dfs(image , i + 1 , j , newColor , oldColor);
dfs(image , i - 1 , j , newColor , oldColor);
dfs(image , i , j + 1 , newColor , oldColor);
dfs(image , i , j - 1 , newColor , oldColor);
}
2.3 完整代码
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
dfs(image , sr , sc , newColor , image[sr][sc]);
return image;
}
private void dfs(int[][] image, int i, int j, int newColor , int oldColor){
int row = image.length;
int col = image[0].length;
if(i < 0 || i >= row || j < 0 || j >= col || image[i][j] != oldColor || image[i][j] == newColor){
return ;
}
image[i][j] = newColor;
dfs(image , i + 1 , j , newColor , oldColor);
dfs(image , i - 1 , j , newColor , oldColor);
dfs(image , i , j + 1 , newColor , oldColor);
dfs(image , i , j - 1 , newColor , oldColor);
}
}
2.4 运行结果
🍁 类似题目推荐:
如果文章对各位大佬有帮助就支持一下噢,不好的地方请各位大佬多多指教!