Color Circle
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
爆搜!!!
#pragma comment(linker, "/STACK:1024000000,1024000000") #include<iostream> #include<cstdio> #include<cmath> #include<string> #include<queue> #include<algorithm> #include<stack> #include<cstring> #include<vector> #include<list> #include<set> #include<map> using namespace std; #define ll long long #define pi (4*atan(1.0)) #define eps 1e-4 #define bug(x) cout<<"bug"<<x<<endl; const int N=1e2+10,M=1e6+10,inf=2147483647; const ll INF=1e18+10,mod=2147493647; ///数组大小 char a[N][N],vis[N][N]; int n,m,ans; int xx[4]={0,1,0,-1}; int yy[4]={1,0,-1,0}; int check(int x,int y) { if(x<=0||x>n||y<=0||y>m) return 0; return 1; } void dfs(int x,int y,int dep) { if(ans)return; for(int i=0;i<4;i++) { int xxx=x+xx[i]; int yyy=y+yy[i]; if(check(xxx,yyy)&&a[xxx][yyy]==a[x][y]) { if(vis[xxx][yyy]&&dep-vis[xxx][yyy]+1>=4) { ans=1; } else if(!vis[xxx][yyy]) { vis[xxx][yyy]=dep; dfs(xxx,yyy,dep+1); vis[xxx][yyy]=0; } } } } int main() { while(~scanf("%d%d",&n,&m)) { memset(vis,0,sizeof(vis)); ans=0; for(int i=1;i<=n;i++) scanf("%s",a[i]+1); for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { dfs(i,j,1); if(ans)break; } if(ans)break; } if(ans)printf("Yes\n"); else printf("No\n"); } return 0; }