510B. Fox And Two Dots - Codeforces Solution C++

  Problem Link : 510B. Fox And Two Dots 


✅ C++ Solution :

 
#include<bits/stdc++.h>

using namespace std;

int lc[]={-1,1,0,0};
int rc[]={0,0,-1,1};

char arr[60][60];
bool visited[60][60];

bool func(int x,int y,char color,int px,int py,int n,int m)
{
	for(int i=0;i<4;i++)
	{
		int p=x+lc[i];
		int q=y+rc[i];
		if(p>=n || p<0 || q>=m || q<0)
			continue;
		if(!visited[p][q] && arr[p][q]==color)
		{
			visited[p][q]=1;
			if(func(p,q,color,x,y,n,m))
				return 1;
		}
		else if(visited[p][q] && (p!=px || q!=py) && arr[p][q]==color)
			return 1;

	}
	return 0;

}

int main()
{
	int n,m;
	cin>>n>>m;
	for(int i=0;i<n;i++)
	{
		for(int j=0;j<m;j++)
			cin>>arr[i][j];
	}

	memset(visited,0,sizeof(visited));

	bool flag=0;

	for(int i=0;i<n;i++)
	{
		for(int j=0;j<m;j++)
		{
			if(!visited[i][j])
			{
				visited[i][j]=1;
				if(func(i,j,arr[i][j],-1,-1,n,m))
				{
					flag=1;
					break;
				}
			}
		}
		if(flag)
			break;
	}
	if(flag)
		cout<<"Yes";
	else
		cout<<"No";
}

 

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!!