From 52287febe41b26d5459b934d9aae8cb5c0b47342 Mon Sep 17 00:00:00 2001 From: msms <44134797+maitreyi0505@users.noreply.github.com> Date: Tue, 6 Oct 2020 17:05:48 +0530 Subject: [PATCH] Create Flood Fill Algorithm (C++).cpp Input for the code: 4 5 1 3 1 2 2 1 2 2 2 3 2 1 1 2 1 3 1 2 2 2 3 2 8 Output: Updated screen after call to floodFill: 1 3 1 8 8 1 8 8 8 3 2 1 1 8 1 3 1 8 8 8 --- .../Flood Fill Algorithm (C++).cpp | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 Flood Fill Algo/Flood Fill Algorithm (C++).cpp diff --git a/Flood Fill Algo/Flood Fill Algorithm (C++).cpp b/Flood Fill Algo/Flood Fill Algorithm (C++).cpp new file mode 100644 index 0000000..7ea18a3 --- /dev/null +++ b/Flood Fill Algo/Flood Fill Algorithm (C++).cpp @@ -0,0 +1,63 @@ +// Flood fill algorithm in C++ using Queue + +#include +using namespace std; + +void checkAndPush(int x,int y, int r, int c, int prevC, int newC, queue>&q, vector> &screen) +{ + if(x<0 || y<0 || x>=r || y>=c || screen[x][y]!=prevC) + return; + + screen[x][y]=newC; + q.push(make_pair(x,y)); + return; +} + +//Driver code +int main() { + int r,c,i,j,x,y,prevC,newC; + queue>q; + pair cur; + + cin>>r>>c; + vector> screen(r) ; + + //input the screen array + for(i=0;irow(c); + for(j=0;j>row[j]; + screen[i]=row; + } + + cin>>x>>y; + prevC=screen[x][y]; + + cin>>newC; + + //push first position pair to queue + checkAndPush(x,y,r,c,prevC,newC,q,screen); + + while(!q.empty()) + { + cur=q.front(); + q.pop(); + x=cur.first; + y=cur.second; + + //fill adjacent cells + checkAndPush(x-1,y,r,c,prevC,newC,q,screen); + checkAndPush(x+1,y,r,c,prevC,newC,q,screen); + checkAndPush(x,y-1,r,c,prevC,newC,q,screen); + checkAndPush(x,y+1,r,c,prevC,newC,q,screen); + } + cout<<"Updated screen after call to floodFill: \n"; + for (i = 0; i < r; i++) + { + for (j = 0; j < c; j++) + cout<