xinyu04

导航

LeetCode 733 Flood Fill BFS模板

An image is represented by an m x n integer grid image where image[i][j] represents the pixel value of the image.

You are also given three integers sr, sc, and color. You should perform a flood fill on the image starting from the pixel image[sr][sc].

To perform a flood fill, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with color.

Return the modified image after performing the flood fill.

Solution

点击查看代码
class Solution {
private:
    int vis[52][52];
    int dir[4][2]={0,1, 1,0, -1,0, 0,-1};
    
    bool check(int x, int y, int r, int c){
        if(x<0||y<0||x>=r||y>=c)return false;
        return true;
    }
    
    queue<vector<int>> q;
    
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {
        
        q.push({sr,sc});
        int origin = image[sr][sc];
        int r = image.size(), c = image[0].size();
        
        while(!q.empty()){
            auto a = q.front();q.pop();
            int x = a[0], y = a[1];
            // already visited
            if(vis[x][y])continue;
            
            if(image[x][y]==origin){
                vis[x][y] = 1;
                image[x][y] = color;
                for(int i=0;i<4;i++){
                    int nx = x+dir[i][0], ny = y+dir[i][1];
                    if(check(nx,ny,r,c)){
                        if(!vis[nx][ny])q.push({nx,ny});
                    }
                }
            }
            
        }
        return image;
    }
};

posted on 2022-07-21 15:14  Blackzxy  阅读(36)  评论(0编辑  收藏  举报