Fox And Two Dots
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
3 4
AAAA
ABCA
AAAA
Yes
3 4
AAAA
ABCA
AADA
No
4 4
YYYR
BYBY
BBBY
BBBY
Yes
7 6
AAAAAB
ABBBAB
ABAAAB
ABABBB
ABAAAB
ABBBAB
AAAAAB
Yes
2 13
ABCDEFGHIJKLM
NOPQRSTUVWXYZ
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).
代码:
1 #include<cstdio> 2 #include<cstring> 3 #include<algorithm> 4 using namespace std; 5 char a[55][55]; 6 int v[55][55]; 7 int fx[4]={0,0,1,-1},fy[4]={1,-1,0,0}; 8 int n,m,ans,e1,e2; 9 int dfs(int x,int y,int nol) 10 { 11 if(ans) return ans; 12 v[x][y]=1; 13 for(int i=0;i<4;i++) 14 {int xx,yy; 15 xx=x+fx[i]; 16 yy=y+fy[i]; 17 if(xx==e1&&yy==e2&&nol>2) 18 {ans=1; 19 return ans; 20 21 } 22 if(xx>=0&&yy>=0&&xx<n&&yy<m&&a[xx][yy]==a[x][y]&&!v[xx][yy]) 23 dfs(xx,yy,nol+1); 24 25 } 26 27 28 } 29 int main() 30 { 31 32 scanf("%d %d",&n,&m); 33 for(int i=0;i<n;i++) 34 scanf("%s",a[i]); 35 36 ans=0; 37 for(int i=0;i<n&&!ans;i++) 38 for(int j=0;j<m&&!ans;j++) 39 { 40 memset(v,0,sizeof(v)); 41 e1=i; 42 e2=j; 43 dfs(i,j,0); 44 45 46 47 } 48 if(ans) printf("Yes\n"); 49 else printf("No\n"); 50 return 0; 51 }