0 0 vote
Article Rating
Subscribe
提醒
guest
2 评论
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
sunznx
class Solution {
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
        int raw = image.size();
        int col = image[0].size();
        vector<vector<bool>> v(raw, vector<bool>(col, false));


        dfs(image, v, sr, sc, image[sr][sc], newColor);


        return image;
    }


    void dfs(vector<vector<int>>& image, vector<vector<bool>>& v, int x, int y, int oldColor, int newColor) {
        int raw = image.size();
        int col = image[0].size();


        if (x < 0 || y < 0 || x >= raw || y >= col || v[x][y] == true || image[x][y] != oldColor) {
            return;
        }


        v[x][y] = true;


        image[x][y] = newColor;
        dfs(image, v, x, y+1, oldColor, newColor);
        dfs(image, v, x, y-1, oldColor, newColor);
        dfs(image, v, x+1, y, oldColor, newColor);
        dfs(image, v, x-1, y, oldColor, newColor);
    }
};


胡小旭
class Solution {
public:
    void dfs(vector<vector<int>>& image, int sr, int sc, int oldColor, int newColor) {
        if (image[sr][sc] != oldColor) return;
        image[sr][sc] = newColor;
        int d[5] = {0,1,0,-1,0};
        for (int i=0;i<4;++i) {
            int nr=sr+d[i];
            int nc=sc+d[i+1];
            if (nr<0||nc<0||nr>=image.size()||nc>=image[0].size()) continue;
            dfs(image,nr,nc,oldColor,newColor);
        }
    }
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
        if (image[sr][sc]==newColor)return image;
        dfs(image,sr,sc,image[sr][sc],newColor);
        return image;
    }
};