-
Notifications
You must be signed in to change notification settings - Fork 0
/
Flood Fill.cpp
118 lines (90 loc) · 1.83 KB
/
Flood Fill.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin>>t;
while(t--)
{
int m,n,i,j,x,y,k;
cin>>n>>m;
int a[n][m];
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
cin>>a[i][j];
}
cin>>x>>y>>k;
if(x<n && y<m)
{
queue<pair<int,int>> q;
q.push({x,y});
int value=a[x][y];
while(!q.empty())
{
pair<int,int> p=q.front();
q.pop();
int c=p.first;
int d=p.second;
a[c][d]=k;
if(c+1<n && a[c+1][d]==value)
q.push({c+1,d});
if(d+1<m && a[c][d+1]==value)
q.push({c,d+1});
if(c-1>=0 && a[c-1][d]==value)
q.push({c-1,d});
if(d-1>=0 && a[c][d-1]==value)
q.push({c,d-1});
}
}
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
## using recursion
#include <bits/stdc++.h>
using namespace std;
void floodfill(vector<vector<int>>& a,int x,int y,int k,int val)
{
if(x>=a.size() || y>=a[0].size() || x<0 || y<0)
return;
if(a[x][y]!=val)
return;
a[x][y]=k;
floodfill(a,x+1,y,k,val);
floodfill(a,x-1,y,k,val);
floodfill(a,x,y+1,k,val);
floodfill(a,x,y-1,k,val);
}
int main() {
int t;
cin>>t;
while(t--)
{
int i,j,x,y,k,m,n;
cin>>n>>m;
vector<vector<int>> a(n,vector<int>(m,0));
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
cin>>a[i][j];
}
cin>>x>>y>>k;
if(x<n && y<m)
{
int val=a[x][y];
floodfill(a,x,y,k,val);
}
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}