Description
There are colorful flowers in the parterre in front of the door of college and form many beautiful patterns. Now, you want to find a circle consist of flowers with same color. What should be done ?
Assuming the flowers arranged as matrix in parterre, indicated by a N*M matrix. Every point in the matrix indicates the color of a flower. We use the same uppercase letter to represent the same kind of color. We think a sequence of points d1, d2, … dk makes up a circle while:
1. Every point is different.
2. k >= 4
3. All points belong to the same color.
4. For 1 <= i <= k-1, di is adjacent to di+1 and dk is adjacent to d1. ( Point x is adjacent to Point y while they have the common edge).
N, M <= 50. Judge if there is a circle in the given matrix.
Input
There are multiply test cases.
In each case, the first line are two integers n and m, the 2nd ~ n+1th lines is the given n*m matrix. Input m characters in per line.
Output
Output your answer as “Yes” or ”No” in one line for each case.
Sample Input
3 3
AAA
ABA
AAA
Sample Output
Yes
求圖中是否有一個環路,其中的字母都相同
爆搜
#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <cstdio>
#include <set>
#include <math.h>
#include <algorithm>
#include <queue>
#include <iomanip>
#include <map>
#include <cctype>
#define INF 0x3f3f3f3f
#define MAXN 1000005
#define Mod 1000000007
using namespace std;
int n,m;
char mp[55][55];
int vis[55][55];
int dx[]={1,-1,0,0};
int dy[]={0,0,1,-1};
bool dfs(int x,int y,char tag,int step,int prex,int prey)
{
int tx,ty;
vis[x][y]=1;
if(step>=4)
{
for(int i=0;i<4;++i)
{
tx=x+dx[i];
ty=y+dy[i];
if(tx<1||tx>n||ty<1||ty>m)
continue;
if((tx!=prex||ty!=prey)&&mp[tx][ty]==tag&&vis[tx][ty])
return true;
}
}
for(int i=0;i<4;++i)
{
tx=x+dx[i];
ty=y+dy[i];
if(tx<1||tx>n||ty<1||ty>m)
continue;
if((tx!=prex||ty!=prey)&&mp[tx][ty]==tag&&!vis[tx][ty])
{
vis[tx][ty]=1;
if(dfs(tx,ty,tag,step+1,x,y))
return true;
}
}
return false;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
for(int i=1;i<=n;++i)
scanf("%s",mp[i]+1);
memset(vis,0,sizeof(vis));
int flag=0;
for(int i=1;i<=n;++i)
{
for(int j=1;j<=m;++j)
{
if(!vis[i][j])
{
flag=dfs(i,j,mp[i][j],1,i,j);
if(flag)
break;
}
}
if(flag)
break;
}
if(flag)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}