颜色填充(DFS)-CSDN博客

29 阅读1分钟

 该题也是非常经典了,也是标准模板题,套入模板写代码即可~~~~~~~~~~~~~~~~~~~~~~~~~~


class Solution {
public:
    vector<vector<int>> book;
    int next[4][2] = {{0,1}, {1,0}, {-1,0}, {0,-1}};
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
        // 准备用深度优先搜索填充
        if (image[sr][sc] != newColor){    //有些不需要变换颜色,直接返回
            helpfunc(image, sr, sc, image[sr][sc], newColor);
        } 
        return image;
    }

    void helpfunc(vector<vector<int>>& image, int x, int y, int oldColor, int newColor){
        if (x < 0 || x >= image.size() || y < 0 || y >= image[0].size() || image[x][y] != oldColor){
            return;
        }
        image[x][y] = newColor;
        for (int k = 0; k < 4; k++){
            helpfunc(image, x + next[k][0], y + next[k][1], oldColor, newColor);
        }

    }
};