No.194 - LeetCode733. Flood Fill - BFS或DFS模版题 - 核心思想染色

class Solution {
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
        const int dirx[] = {-1,0,1,0};
        const int diry[] = {0,-1,0,1};
        int a = image.size();
        int b = image[0].size();
        vector<vector<int>> flag(a,vector<int>(b,0));
        queue<pair<int,int>> q;
        q.push(make_pair(sr,sc));
        flag[sr][sc] = 1;
        while(!q.empty()){
            int x = q.front().first;
            int y = q.front().second;
            flag[x][y] = 1;
            for(int i=0;i<4;i++){
                int xx = x+dirx[i];
                int yy = y+diry[i];
                if(xx < 0 || yy < 0 || xx >= a || yy >= b){
                    continue;
                }
                if(flag[xx][yy] == 0 && image[x][y] == image[xx][yy]){
                    q.push(make_pair(xx,yy));
                }
            }
            image[x][y] = newColor;
            q.pop();
        }
        return image;
    }
};

你可能感兴趣的:(leetcode)