Description
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.
Sample Input
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
Hint
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).
欧拉回路,用bfs搞了一通,发现好乱,学习大神DFS,听房神说还有很简单的方法,明天继续看一下。
1 #include <iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<queue> 6 using namespace std; 7 char maze[55][55]; 8 int vis[55][55]; 9 int n,m; 10 int flag = 0; 11 int to[4][2] = {{1,0},{-1,0},{0,1},{0,-1}}; 12 bool check(int x,int y){ 13 if(x<0||x>=n||y<0||y>=m) return false; 14 //if(vis[x][y]) return false; 15 return true; 16 } 17 void dfs(int x,int y,int prex,int prey){ 18 if(!check(x,y)) return; 19 vis[x][y] = 1; 20 int postx,posty; 21 for(int i = 0; i<4; i++){ 22 postx = x + to[i][0]; 23 posty = y + to[i][1]; 24 if(check(postx,posty)&&maze[postx][posty] == maze[x][y]&&(postx!=prex||posty!=prey)){ 25 if(vis[postx][posty]){ 26 flag = 1; 27 return; 28 } 29 dfs(postx,posty,x,y); 30 } 31 } 32 } 33 void input(){ 34 35 scanf("%d%d",&n,&m); 36 for(int i = 0; i<n; i++) scanf("%s",maze[i]); 37 for(int i = 0; i<n; i++){ 38 for(int j = 0; j<m; j++){ 39 if(!vis[i][j]){ 40 dfs(i,j,-1,-1); 41 } 42 } 43 } 44 if(flag) printf("Yes "); 45 else printf("No "); 46 } 47 int main() 48 { 49 input(); 50 return 0; 51 }