E

题目链接:http://acm.hust.edu.cn/vjudge/contest/127946#problem/E

分析:存在某个字符能围成封闭图形,则说明Yes,否则是No。

Sample Input
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

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).

*********************************************

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 #include <cmath>
 6 
 7 using namespace std;
 8 
 9 #define N 1200
10 
11 int v[N][N],n,m,ww,cnt;
12 char s[60][60];
13 int dir[4][2]= { {1,0},{-1,0},{0,1},{0,-1} };
14 
15 void q(char ch,int x,int y,int X,int Y)
16 {
17     int i,xx,yy;
18     if(ww==1)
19         return ;
20 
21     for(i=0; i<4; i++)
22     {
23         xx=x+dir[i][0];
24         yy=y+dir[i][1];
25         if(xx==X&&yy==Y)
26             continue ;
27         if(xx>=0&&xx<n&&yy>=0&&yy<m&&s[xx][yy]==ch&&v[xx][yy])
28         {
29             ww=1;
30            return ;
31         }
32          if(xx>=0&&xx<n&&yy>=0&&yy<m&&s[xx][yy]==ch&&!v[xx][yy])
33         {
34             v[xx][yy]=1;
35             q(ch,xx,yy,x,y);
36         }
37     }
38 }
39 
40 int main()
41 {
42     int i,j;
43 
44     while(scanf("%d %d", &n, &m) != EOF)
45     {
46         ww=0,cnt=0;
47         memset(v,0,sizeof(v));
48         for(i=0; i<n; i++)
49             scanf("%s", s[i]);
50 
51         for(i=0; i<n; i++)
52         {
53             for(j=0; j<m; j++)
54             {
55                 if(v[i][j]==0)
56                 {
57                     v[i][j]=1;
58                     q(s[i][j],i,j,0,0);
59                     if(ww==1)
60                     {
61                        cnt=1;
62                        break;
63                     }
64                 }
65             }
66         }
67         if(cnt==1)
68             printf("Yes
");
69         else
70             printf("No
");
71     }
72     return 0;
73 }
原文地址:https://www.cnblogs.com/weiyuan/p/5768057.html