前言:小白入门题解,算法大佬可以直接跳过此博客(大佬轻喷哈)
题源: 力扣(LeetCode)https://leetcode-cn.com/problems/flood-fill/
题目描述:
有一幅以二维整数数组表示的图画,每一个整数表示该图画的像素值大小,数值在 0 到 65535 之间。
给你一个坐标 (sr, sc) 表示图像渲染开始的像素值(行 ,列)和一个新的颜色值 newColor,让你重新上色这幅图像。
为了完成上色工作,从初始坐标开始,记录初始坐标的上下左右四个方向上像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应四个方向上像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为新的颜色值。
最后返回经过上色渲染后的图像。
**思路:**深度优先,先向上,上到顶了向左,向左到头了,然后向下,最后向右,如此重复。递归的出口是:如果一个位置已经被染过色了或者该位置的相素值不等于起始点相素值,结束染色, return 。 详情看代码
C++ 版代码:
class Solution {
public:
vector<vector<int> > floodFill(vector<vector<int> >& image, int sr, int sc, int newColor) {
int colCount = image[0].size() - 1; // 列的索引范围
int rowCount = image.size() - 1; // 行的索引范围
int startPixel = image[sr][sc]; // 获得起始位置的像素值
DFS(image, startPixel, sr, sc, newColor, rowCount, colCount);
return image;
}
void DFS(vector<vector<int> >& image, int startPixel, int sr, int sc, int newColor,int rowCount,int colCount){
// 如果一个位置的四周都染上了色或者不等于起始位置的像素值,则结束染色
if(image[sr][sc] == newColor || image[sr][sc] != startPixel )
return;
if(image[sr][sc] == startPixel) // 如果等于起始位置像素值
image[sr][sc] = newColor; // 染色
if(sr-1 >= 0){ // 如果向上数组还没有越界
DFS(image, startPixel, sr - 1, sc, newColor, rowCount, colCount); // 向上染色
}
if(sc-1 >= 0 ){ // 如果向左数组还没有越界
DFS(image, startPixel, sr, sc - 1, newColor, rowCount, colCount); // 向左染色
}
if(sr+1 <= rowCount){ // 如果向下数组还没有越界
DFS(image, startPixel, sr + 1, sc, newColor, rowCount, colCount); // 向下染色
}
if(sc+1 <= colCount){ // 如果向右数组还没有越界
DFS(image, startPixel, sr, sc + 1, newColor, rowCount, colCount); // 向右染色
}
}
};
Java 版代码:
class Solution {
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
int rowCount = image.length - 1; // 行的索引范围
int colCount = image[0].length - 1; // 列的索引范围
int startPixel = image[sr][sc]; // 起始点相素值
DFS(image, sr, sc, newColor, startPixel, rowCount, colCount);
return image;
}
public void DFS(int[][] image, int sr, int sc, int newColor,int startPixel,int rowCount,int colCount) {
// 如果一个位置已经被染过色了或者该位置的相素值不等于起始点相素值,结束染色, return (递归的出口)
if(image[sr][sc] == newColor || image[sr][sc] != startPixel) {
return;
}
if(image[sr][sc] == startPixel) { //如果一个位置的相素值等于起始点相素值,染色
image[sr][sc] = newColor;
}
if(sr - 1 >= 0) { // 如果向上数组还没有越界
DFS(image, sr-1, sc, newColor, startPixel, rowCount, colCount); // 向上染色
}
if(sc - 1 >= 0) { // 如果向左数组还没有越界
DFS(image, sr, sc-1, newColor, startPixel, rowCount, colCount); // 向左染色
}
if(sr + 1 <= rowCount) { // 如果向下数组还没有越界
DFS(image, sr+1, sc, newColor, startPixel, rowCount, colCount); // 向下染色
}
if(sc + 1 <= colCount) { // 如果向右数组还没有越界
DFS(image, sr, sc+1, newColor, startPixel, rowCount, colCount); // 向右染色
}
}
}