Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Wednesday, July 19, 2017

Flood Fill Algorithm Geeks


Problem:
Given a 2D screen, location of a pixel in the screen ie(x,y) and a color(K), your task is to replace color of the given pixel and all adjacent same colored pixels with the given color K.

Idea is to recursively track all the vertices adjacent to the current vertex.

Code:
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
 {
     private static int m,n;
     public static void change(int graph[][],int x,int y,int k,int old)
     {
         if(x<0 || y>=n || x>=m || y<0)
         return;
         if(graph[x][y]!=old)
         return;
            graph[x][y]=k;
            change(graph,x+1,y,k,old);
            change(graph,x-1,y,k,old);
            change(graph,x,y+1,k,old);
            change(graph,x,y-1,k,old);
       
     }
public static void main (String[] args)
{
Scanner ab=new Scanner(System.in);
int t=ab.nextInt();
while(t-->0)
{
    m=ab.nextInt();
    n=ab.nextInt();
   int graph[][]=new int[m][n];
   for(int i=0;i<m;i++)
   for(int j=0;j<n;j++)
   graph[i][j]=ab.nextInt();
   int x=ab.nextInt();
   int y=ab.nextInt();
   change(graph,x,y,ab.nextInt(),graph[x][y]);
    for(int i=0;i<m;i++)
   for(int j=0;j<n;j++)
   System.out.print(graph[i][j]+" ");
   System.out.println();
}
}
}

0 Comments:

Post a Comment

Stats