Skip to main content

Flood Fill Algorithm

Task: Given a 2D screen, location of a pixel in the screen ie(x, y) and a color K, Replace color of the given pixel and all adjacent ( excluding diagonally adjacent ) same colored pixels with the given color K.

Example:
Input:
1
2 2
1 1 1 1
0 1 8
Output:
8 8 8 8

Here is the Code:
Program in C++:

  1. #include<iostream>
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4. int main()
  5.  {
  6. int t;
  7. cin>>t;
  8. while(t--)
  9. {
  10.     int n,m;
  11.     cin>>n>>m;
  12.     int a[n][m];
  13.     for(int i=0;i<n;i++)
  14.     {
  15.         for(int j=0;j<m;j++)
  16.         {
  17.             cin>>a[i][j];
  18.         }
  19.     }
  20.     int x,y,k;
  21.     cin>>x>>y>>k;
  22.     queue<pair<int,int>> q;
  23.     q.push(make_pair(x,y));
  24.     int t1 = a[x][y];
  25.     a[x][y]=k;
  26.     while(q.empty()==false)
  27.     {
  28.         pair<int,int> t2 = q.front();
  29.         int i = t2.first, j = t2.second;
  30.         if(a[i-1][j]==t1&&i-1>=0)
  31.         {
  32.             q.push(make_pair(i-1,j));
  33.             a[i-1][j]=k;
  34.         }
  35.         if(a[i][j-1]==t1&&j-1>=0)
  36.         {
  37.             q.push(make_pair(i,j-1));
  38.             a[i][j-1]=k;
  39.         }
  40.         if(a[i][j+1]==t1&&j+1<m)
  41.         {
  42.             q.push(make_pair(i,j+1));
  43.             a[i][j+1]=k;
  44.         }
  45.         if(a[i+1][j]==t1&&i+1<n)
  46.         {
  47.             q.push(make_pair(i+1,j));
  48.             a[i+1][j]=k;
  49.         }
  50.         q.pop();
  51.     }
  52.     for(int i=0;i<n;i++)
  53.     {
  54.         for(int j=0;j<m;j++)
  55.         {
  56.             cout<<a[i][j]<<" ";
  57.         }
  58.     }
  59.     cout<<endl;
  60. }
  61. return 0;
  62. }


Here is the Video: