Flood fill Algorithm | Practice | GeeksforGeeks

An image is represented by a 2-D array of integers, each integer representing the pixel value of the image.
Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, "flood fill" the image.
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 as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.
Example 1:
Input: image = {{1,1,1},{1,1,0},{1,0,1}},
sr = 1, sc = 1, newColor = 2.
Output: {{2,2,2},{2,2,0},{2,0,1}}
Explanation: From the center of the image 
(with position (sr, sc) = (1, 1)), all 
pixels connected by a path of the same color
as the starting pixel are colored with the new 
color.Note the bottom corner is not colored 2, 
because it is not 4-directionally connected to 
the starting pixel.

 
Your Task:
You don't need to read or print anyhting. Your task is to complete the function floodFill() which takes image, sr, sc and newColor as input paramater and returns the image after flood filling.
 
Expected Time Compelxity: O(n*m)
Expected Space Complexity: O(n*m)
 
0
aligrewal2113 hours ago
TC = (n*m)
SC = O(1)
void DFS(vector<vector<int>>& image,int i, int j, int initialColor, int newColor)
    {
        if(i<0 || j<0 || i>=image.size() || j>=image[0].size() 
        || image[i][j] != initialColor) return;
        image[i][j] = newColor;
        DFS(image, i+1, j, initialColor, newColor);
        DFS(image, i, j+1, initialColor, newColor);
        DFS(image, i-1, j, initialColor, newColor);
        DFS(image, i, j-1, initialColor, newColor);   
    }
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {
        // Code here 
        int initialColor = image[sr][sc];
        if(image[sr][sc] != newColor)
            DFS(image, sr, sc, initialColor, newColor);
        return image;
    }
+1
bhagatkumar752 days ago
PYTHON CODE: Using DFS
class Solution:
    def floodFill(self, image, sr, sc, newColor):
        M=len(image)
        N=len(image[0])
        visited=[[0]*(N) for i in range(M)]
        
        def DFS(i,j,visited, newColor, M,N,oldColor):
            if i<0 or j<0 or i>=M or j>=N :
                return
            elif visited[i][j]==1 or image[i][j]!=oldColor:
                return
            visited[i][j]=1
            image[i][j]=newColor
            
            DFS(i+1,j,visited, newColor, M,N, oldColor)
            DFS(i-1,j,visited, newColor, M,N ,oldColor)
            DFS(i,j-1,visited, newColor, M,N, oldColor)
            DFS(i,j+1,visited, newColor, M,N ,oldColor)
        
        oldColor=image[sr][sc]
        DFS(sr,sc,visited, newColor, M,N, oldColor)
        return image
+1
bhagatkumar752 days ago
PYTHON CODE: Using BFS
class Solution:
    
	def floodFill(self, image, sr, sc, newColor):
		M=len(image)
		N=len(image[0])
        visited=[[0]*(N) for i in range(M)]
        q=[]
        oldColor=image[sr][sc]
        q.append([sr,sc])
        image[sr][sc]=newColor
        while q:
            temp=q.pop(0)
            i=temp[0]
            j=temp[1]
            
            if i>=0 and (j+1)>=0 and i<M and (j+1)<N and visited[i][j+1]==0 and image[i][j+1]==oldColor:
                q.append([i, j+1])
                visited[i][j+1]=1
                image[i][j+1]=newColor
                
            if i>=0 and (j-1)>=0 and i<M and (j-1)<N and visited[i][j-1]==0 and image[i][j-1]==oldColor:
                q.append([i, j-1])
                visited[i][j-1]=1
                image[i][j-1]=newColor
                
            if (i+1)>=0 and (j)>=0 and (i+1)<M and (j)<N and visited[i+1][j]==0 and image[i+1][j]==oldColor:
                q.append([i+1, j])
                visited[i+1][j]=1
                image[i+1][j]=newColor
                
            if (i-1)>=0 and (j)>=0 and (i-1)<M and (j)<N and visited[i-1][j]==0 and image[i-1][j]==oldColor:
                q.append([i-1, j])
                visited[i-1][j]=1
                image[i-1][j]=newColor
    
        return image
0
harshmaurya11520015 days ago
void dfs(vector<vector<int>>& adj,vector<vector<int>>&vis,int i,int j,int c,int m,int n,int v){   if(i<0||j<0||i>m-1||j>n-1)   return ;      if(vis[i][j]==0)   {       vis[i][j]=1;       if(adj[i][j]==v)       {           adj[i][j]=c;                      dfs(adj,vis,i-1,j,c,m,n,v);           dfs(adj,vis,i+1,j,c,m,n,v);           dfs(adj,vis,i,j-1,c,m,n,v);           dfs(adj,vis,i,j+1,c,m,n,v);       }   }   return;}   vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {     int m=image.size(),n=image[0].size();     vector<vector<int>>vis(m,vector<int>(n,0));    int v=image[sr][sc];      dfs(image,vis,sr,sc, newColor,m,n,v);     return image;   }};
0
bhanupragnya2 weeks ago
EASY JAVA SOLUTION :
class Solution
{
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor)
    {

        
        int c=image[sr][sc];
        image[sr][sc]=newColor;
        if(sr<0 || sc<0 || sr==image.length || sc==image[0].length || c==newColor) return image;
        if((sr-1)>=0 && image[sr-1][sc]==c) image=floodFill(image,sr-1,sc,newColor);
        if((sr+1)<image.length && image[sr+1][sc]==c) image=floodFill(image,sr+1,sc,newColor);
        if((sc-1)>=0 && image[sr][sc-1]==c) image=floodFill(image,sr,sc-1,newColor);
        if((sc+1)<image[0].length && image[sr][sc+1]==c) image=floodFill(image,sr,sc+1,newColor);
        return image;
    }
}
0
sohanpulluru2 weeks ago
void dfs(vector<vector<int>>& image, int sr, int sc, int ic, int nc)   {       if(sr < 0 || sr >= image.size()) return;       if(sc < 0 || sc >= image[0].size()) return;       if(image[sr][sc] != ic) return;       image[sr][sc] = nc;       dfs(image, sr+1, sc, ic, nc);       dfs(image, sr-1, sc, ic, nc);       dfs(image, sr, sc+1, ic, nc);       dfs(image, sr, sc-1, ic, nc);   }   vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor)   {       // Code here        if(image[sr][sc] == newColor) return image;       dfs(image, sr, sc, image[sr][sc], newColor);       return image;   }
+1
shubhamrikhari86512 weeks ago
void solve(vector<vector<int>>& image, int i, int j, int n, int m, int color, int newColor) {       if(i>=0 && i<n && j>=0 && j<m && image[i][j] == color) {}        else {           return;       }       image[i][j] = newColor;       solve(image, i+1, j, n, m, color, newColor);       solve(image, i-1, j, n, m, color, newColor);       solve(image, i, j+1, n, m, color, newColor);       solve(image, i, j-1, n, m, color, newColor);       return;   }   vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor) {       int n = image.size();       int m = image[0].size();       int color = image[sr][sc];       if(color == newColor) {           return image;       }       solve(image, sr, sc, n, m, color, newColor);       return image;   }
0
divyanshjain2003kanpur2 weeks ago
Java O(n) solution using BFS:
 
class Pair{   int i,j;   Pair(int a,int b){       i=a;       j=b;   }}class Solution{   public int[][] bfs(int[][] image,Pair src,int newColor,int r,int c,int h)   {       Queue<Pair> q=new LinkedList<>();       q.add(src);       if(newColor==h)       return image;       image[src.i][src.j]=newColor;       while(!q.isEmpty())       {           Pair x=q.poll();           if(x.i-1>=0 && image[x.i-1][x.j]==h)           {               Pair y=new Pair(x.i-1,x.j);               image[x.i-1][x.j]=newColor;               q.add(y);           }           if(x.j-1>=0 && image[x.i][x.j-1]==h)           {               Pair y=new Pair(x.i,x.j-1);               image[x.i][x.j-1]=newColor;               q.add(y);           }           if(x.i+1<r && image[x.i+1][x.j]==h)           {               Pair y=new Pair(x.i+1,x.j);               image[x.i+1][x.j]=newColor;               q.add(y);           }           if(x.j+1<c && image[x.i][x.j+1]==h)           {               Pair y=new Pair(x.i,x.j+1);               image[x.i][x.j+1]=newColor;               q.add(y);           }       }       return image;   }   public int[][] floodFill(int[][] image, int sr, int sc, int newColor)   {       int r=image.length;       int c=image[0].length;       Pair src=new Pair(sr,sc);       bfs(image,src,newColor,r,c,image[sr][sc]);       return image;       // Code here    }}
0
chamoli2 weeks ago
class Solution {
private:
    void Painter(vector<vector<int>> &image,int i,int j,int color,int row,int col,int validColor){
        
        // base case
        // checking if we are out of bound or image we are on is already visited or we stand on wrong pixel
        
        if(i < 0 or j < 0 or i >= row or j >= col or image[i][j] != validColor){
            return;
        }
        
        // if image is valid image , than paint it
        image[i][j] = color;
        
        // travel 
        Painter(image,i-1,j,color,row,col,validColor); // Up
        Painter(image,i+1,j,color,row,col,validColor); // down
        Painter(image,i,j-1,color,row,col,validColor); // left
        Painter(image,i,j+1,color,row,col,validColor); // right
        
    }
public:
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color) {
         // size of row and col
        int row = image.size();
        int col = image[0].size();
        
        // valid color which can be colored
        int validColor = image[sr][sc];
        
        // if source is already painted
        if(validColor == color){
            return image;
        } 
        
        // calling painter function for help
        Painter(image,sr,sc,color,row,col,validColor);
        
        return image;
    }
};
0
1107khyati3 weeks ago
void flood_fill(vector<vector<int>>&image,int sr,int sc,int old_color,int color)
     {
    
        if(sr>=image.size()||sc>=image[0].size()||sr<0||sc<0||image[sr][sc]==color||image[sr][sc]!=old_color)
        return;
        image[sr][sc]=color;
        flood_fill(image,sr-1,sc,old_color,color);
        flood_fill(image,sr,sc-1,old_color,color);
        flood_fill(image,sr,sc+1,old_color,color);
        flood_fill(image,sr+1,sc,old_color,color);
    
      }
    
    
    vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int newColor)
     {
        int old_color= image[sr][sc];
        flood_fill(image,sr,sc,old_color,newColor);
        return image;
     }
     
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.