Fox Ciel is playing a mobile puzzle game called "Two Dots". The basic levels are played on a board of size n × m cells, like this:
Each cell contains a dot that has some color. We will use different uppercase Latin characters to express different colors.
The key of this game is to find a cycle that contain dots of same color. Consider 4 blue dots on the picture forming a circle as an example. Formally, we call a sequence of dots d1, d2, ..., dk a cycle if and only if it meets the following condition:
- These k dots are different: if i ≠ j then di is different from dj.
- k is at least 4.
- All dots belong to the same color.
- For all 1 ≤ i ≤ k - 1: di and di + 1 are adjacent. Also, dk and d1 should also be adjacent. Cells x and y are called adjacent if they share an edge.
Determine if there exists a cycle on the field.
Input
The first line contains two integers n and m (2 ≤ n, m ≤ 50): the number of rows and columns of the board.
Then n lines follow, each line contains a string consisting of m characters, expressing colors of dots in each line. Each character is an uppercase Latin letter.
Output
Output "Yes" if there exists a cycle, and "No" otherwise.
Example
Input
3 4
AAAA
ABCA
AAAA
Output
Yes
Input
3 4
AAAA
ABCA
AADA
Output
No
Input
4 4
YYYR
BYBY
BBBY
BBBY
Output
Yes
Input
7 6
AAAAAB
ABBBAB
ABAAAB
ABABBB
ABAAAB
ABBBAB
AAAAAB
Output
Yes
Input
2 13
ABCDEFGHIJKLM
NOPQRSTUVWXYZ
Output
No
Note
In first sample test all 'A' form a cycle.
In second sample there is no such cycle.
The third sample is displayed on the picture above ('Y' = Yellow, 'B' = Blue, 'R' = Red).
题意:在一个棋盘里有不同种类的点,用大写的英文字母表示,问你在这个棋盘里是否有同种颜色的点构成的环,构成环的要求:每个点都要相邻并且第一个点要与最后一个点相邻;
思路:我用的dfs写的。。。总体思路就是从一个点出发,当搜索到尽头时就判断是否符合形成环的条件,如果成立就直接返回,不用继续搜索,如不满足条件,那么就将ans清0,否则函数回溯以后的步数将会和之前搜索的步数进行累加,导致结果错误。。。(因为这个错了3遍QAQ);
下面附上我的代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<queue>
using namespace std;
int sx,sy,ex,ey,ny,nx,n,m,ans,ams,flag=0;
int mx[4]={0,0,1,-1};
int my[4]={1,-1,0,0};
int vis[205][205];
char mapp[205][205];
bool check(int x,int y)//判断是否是合法的点
{
if(x<0||y<0||x>=n||y>=m||vis[x][y])
return false;
return true;
}
void dfs(int x,int y)
{
ans++;//记录步数
vis[x][y]=1;
//printf("======%d %d %d %d======\n",sx,sy,ans,ams);
for(int i=0;i<4;i++)
{
nx=x+mx[i];
ny=y+my[i];
if(check(nx,ny))
{
if(mapp[nx][ny]==mapp[x][y])//如果满足条件就继续搜索
dfs(nx,ny);
}
}
if(ans>=4&&((abs(ex-x)==1&&abs(y-ey)==0)||(abs(ex-x)==0&&abs(y-ey)==1)))//判断搜到尽头的那个点是否和起点相邻,步数是否大于4
{
flag=1;
return;
}
else ans=0;//如果不满足条件即回溯到起点重新搜索,这时步数就要清零
}
int main()
{
while(~scanf("%d %d",&n,&m)&&(n||m))
{
flag=0;
for(int i=0;i<n;i++)
scanf("%s",mapp[i]);
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
ans=0;
memset(vis,0,sizeof(vis));//每搜一个点,判断完后都要清除标记,以便后面的点的搜索
if(!vis[i][j])
{
ex=i;
ey=j;
dfs(i,j);
if(flag) break;
}
if(flag) break;
}
if(flag) puts("Yes");
else puts("No");
}
return 0;
}