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
1
2 2
1 1 1 1
0 1 8
Output:
8 8 8 8
Here is the Code:
Program in C++:
- #include<iostream>
- #include<bits/stdc++.h>
- using namespace std;
- int main()
- {
- int t;
- cin>>t;
- while(t--)
- {
- int n,m;
- cin>>n>>m;
- int a[n][m];
- for(int i=0;i<n;i++)
- {
- for(int j=0;j<m;j++)
- {
- cin>>a[i][j];
- }
- }
- int x,y,k;
- cin>>x>>y>>k;
- queue<pair<int,int>> q;
- q.push(make_pair(x,y));
- int t1 = a[x][y];
- a[x][y]=k;
- while(q.empty()==false)
- {
- pair<int,int> t2 = q.front();
- int i = t2.first, j = t2.second;
- if(a[i-1][j]==t1&&i-1>=0)
- {
- q.push(make_pair(i-1,j));
- a[i-1][j]=k;
- }
- if(a[i][j-1]==t1&&j-1>=0)
- {
- q.push(make_pair(i,j-1));
- a[i][j-1]=k;
- }
- if(a[i][j+1]==t1&&j+1<m)
- {
- q.push(make_pair(i,j+1));
- a[i][j+1]=k;
- }
- if(a[i+1][j]==t1&&i+1<n)
- {
- q.push(make_pair(i+1,j));
- a[i+1][j]=k;
- }
- q.pop();
- }
- for(int i=0;i<n;i++)
- {
- for(int j=0;j<m;j++)
- {
- cout<<a[i][j]<<" ";
- }
- }
- cout<<endl;
- }
- return 0;
- }
Here is the Video:
Comments
Post a Comment