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).
#include<stdio.h>
#include<string.h>
int m,n;
int dis[8]={1,0,-1,0,0,1,0,-1};// 方向数组 四个方向
int vis[100][100];
char ch[100][100];
int flag;
void dfs(int x,int y,int fx,int fy)//此处的四个变量代表当前点的坐标和上一個走过的点的坐标
{
flag=0;
int i,j;
int tx,ty;
for(i=0;i<8;i+=2)//四个方向都要遍历
{
tx=x+dis[i];
ty=y+dis[i+1];//将要走的点的坐标
if(tx<0||ty<0||tx>=m||ty>n-1||ch[tx][ty]!=ch[x][y]||tx==fx&&ty==fy)//这些点要满足四个条件 数组不越接界 和与上一个字母相同 没有走回去
continue;
if(vis[tx][ty])//只要找到一个被标记的就成环
{
flag=1;
return ;
}
vis[tx][ty]=1;
dfs(tx,ty,x,y);//此处的三四个变量必须是x,y 不能改变fx,fy的值
}
}
int main()
{
int i,j;
while(scanf("%d %d",&m,&n)!=EOF)
{
for(i=0;i<m;i++)
{
scanf("%s",ch[i]);//此处特别注意 若用%C输入 加 getchar(); 吸收回车
}
for(i=0;i<m&&!flag;i++)//因为每一个点都有可能成为迷宫的起点所以要遍历每一个点
{
for(j=0;j<n;j++)
{
memset(vis,0,sizeof(vis));//清空数组
vis[i][j]=1;//将选出来的点标记上
dfs(i,j,i,j);//进入深搜
if(flag)
break;
}
}
if(flag)
printf("Yes\n");
else
printf("No\n");
}
return 0;
}