1105D. Kilani and the Game - Codeforces Solution C++

  Problem Link : 1105D. Kilani and the Game 


✅ C++ Solution :

 
#include<bits/stdc++.h>
using namespace std;

#define ll long long int

#define pp pair<int,int>
#define mp make_pair

int lt[]={-1,1,0,0};
int rt[]={0,0,-1,1};

bool fun(queue<pp> curr[],int p)
{
	for(int i=1;i<=p;i++)
		if(curr[i].size()>0)
			return 1;
	return 0;	
}

int main()
{
	int n,m,p;
	cin>>n>>m>>p;
	int s[p+1], ans[p+1];
	for(int i=1;i<=p;i++)
	{
		cin>>s[i];
		ans[i]=0;
	}
	
	char arr[n][m];
	queue<pp> curr[p+1];

	for(int i=0;i<n;i++)
		for(int j=0;j<m;j++)
		{
			cin>>arr[i][j];
			if(arr[i][j]>='1' && arr[i][j]<='9')
				curr[arr[i][j]-'0'].push(mp(i,j));
		}

	queue<pp> q;
	int t,sz,x,y;
	pp pr;
	while(fun(curr,p))
	{
		for(int i=1;i<=p;i++)
		{
			q=curr[i];
			t=s[i];
			while(!q.empty() && t--)
			{
				sz=q.size();
				while(sz--)
				{
					pr=q.front();
					q.pop();
					for(int j=0;j<4;j++)
					{
						x=pr.first+lt[j];
						y=pr.second+rt[j];
						if(x>=0 && x<n && y>=0 && y<m && arr[x][y]=='.')
						{
						//    cout<<"aa";
							arr[x][y]=i+48;
						//	cout<<x<<" "<<y<<" "<<arr[x][y]<<endl;
							q.push(mp(x,y));
						}
					}
				}
			}

			curr[i]=q;
		}
	}	
    
  /*  for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
            cout<<arr[i][j]<<" ";
        cout<<endl;    
    }*/
    
	for(int i=0;i<n;i++)
		for(int j=0;j<m;j++)
		{
			if(arr[i][j]>='1' && arr[i][j]<='9')
				ans[arr[i][j]-'0']++;
		}
	for(int i=1;i<=p;i++)
		cout<<ans[i]<<" ";		

}

 

Thank you for your patience reading. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Whatsapp or Facebook. 

😇Happy Learning!!