Fox Ciel is playing a mobile puzzle game called ". The basic levels is played on a board of size n x m cells, like this:
Each cell contains a dot this has some color. We'll use the different uppercase Latin characters to express different colors.
The key of this game was 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 is different:if i ≠ J and di is different fro M DJ.
- K is at least 4.
- All dots belong to the same color.
- For all 1≤ i ≤ k -1: di and di + 1 is Adjac Ent. Also, dK and D1 should Also be adjacent. Cells x and y is called adjacent if they share an edge.
Determine if there exists a cycle on the field.
Input
The first line contains integers n and m (2≤ n, m ≤50): the number O f 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 a uppercase Latin letter.
Output
Output "Yes" if there exists a cycle, and "No" otherwise.
Examplesinput
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).
The main is to use DFS to determine whether to return to the point of departure, and ensure that no backtrack (so the DFS function defines four variables)
#include <cstdio>#include<cstring>intflag[ -][ -];Charstr[ -][ -];intn,m,k;intdx[4]={-1,1,0,0};intdy[4]={0,0,-1,1};voidDfsintXintYintCxintcy) { if(Flag[x][y] = =1) {k=1; return ; } Flag[x][y]=1; intI,nx,ny; for(i =0; I <4; i++) {NX=x+Dx[i]; NY=y+Dy[i]; if(Str[nx][ny] = = Str[x][y] && (NX! = CX | | NY! =cy)) {DFS (nx,ny,x,y); } } }intMain () { while(SCANF ("%d%d", &n,&m)! =EOF) {k=0; inti,j; memset (Flag,0,sizeof(flag)); for(i =1; I <= N; i++) {scanf ("%s", str[i]+1); } for(i =1; I <= N; i++) { for(j =1; J <= M; J + +) { if(Flag[i][j] = =1) Continue; DFS (I,J,I,J); if(k = =1) Break; } if(k = =1) Break; } if(k = =1) printf ("yes\n"); Elseprintf ("no\n"); }}
CF 510b Fox and both Dots