您的位置:首页 > 其它

Codeforces Round #290 (Div. 2) B. Fox And Two Dots

2015-02-04 12:06 429 查看
水题,dfs找环,之前没怎么做搜索的题,看了题解报告才知道环的构成条件!学的太渣了!

B. Fox And Two Dots

time limit per test
2 seconds

memory limit per test
256 megabytes

input
standard input

output
standard output

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 test(s)

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


#include<stdio.h>
#include<string.h>
#define maxn 100

char map1[maxn][maxn];
int step[maxn][maxn];
int visit[maxn][maxn];
int fx[4][2]={{0,1},{0,-1},{-1,0},{1,0}};
int n,m;
int flag=0;

int dfs(int x,int y,char c)
{
int nx,ny;
for(int i=0;i<4;i++)
{
nx=x+fx[i][0];
ny=y+fx[i][1];
if(nx>=0&&nx<n&&ny>=0&&ny<m&&c==map1[nx][ny])
{
if(!visit[nx][ny])
{
visit[nx][ny]=1;
step[nx][ny]=step[x][y]+1;
dfs(nx,ny,c);
}
else if(visit[nx][ny]&&step[nx][ny]-step[x][y]>=1)
{
flag=1;
return 0;
}
}
}
return 0;
}
int main()
{
scanf("%d%d",&n,&m);
memset(visit,0,sizeof(visit));
memset(step,0,sizeof(step));
for(int i=0;i<n;i++)
scanf("%s",map1[i]);
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(!visit[i][j])
{
visit[i][j]=1;
step[i][j]=1;
dfs(i,j,map1[i][j]);
}

if(flag)
break;
}
if(flag)
break;
}
if(flag)
printf("Yes\n");
else
printf("No\n");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: