codeforces 510 B. Fox And Two Dots
http://codeforces.com/contest/510/problem/B 题意:给定一个maze,用不同的字母代表不同的颜色。问能否找到一个颜色相同的环(失少四个点组成) 思路:dfs一遍,如果遇到之前已经访问过的点,说明成环。需要注意的是,要注意由一个点向某方向移动,然后由反方向移动到该点所造成的误判。所以dfs除了要知道当前的坐标x,y,还要记录之前的坐标px,py.
/* ***********************************************
Author :111qqz
Created Time :2015年12月05日 星期六 21时35分07秒
File Name :code/cf/problem/510B.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <set>
8#include <map>
9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define fst first
14#define sec second
15#define lson l,m,rt<<1
16#define rson m+1,r,rt<<1|1
17#define ms(a,x) memset(a,x,sizeof(a))
18typedef long long LL;
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6const int N=55;
7int n,m;
8char maze[N][N];
9bool vis[N][N];
10bool flag;
1bool inmaze( int x,int y)
2{
3 if (x>=0&&x<n&&y>=0&&y<m) return true;
4 return false;
5}
6void dfs( int x,int y,int px,int py) //要记录当前的x,y是由哪里来的。把因为由px,py到x,y再回到px,py引起的误判剔除。
7{ //判cycle方式为:到达一个之前已经到达过的点。
8 vis[x][y] = true;
9 // cout<<"x:"<<x<<" y:"<<y<<" cur:"<<cur<<endl;
10 if (flag) return;
11 for ( int i = 0 ; i < 4 ; i++)
12 {
13 int nx = x + dx4[i] ;
14 int ny = y + dy4[i] ;
15 if (nx==px&&ny==py) continue;
16 if (inmaze(nx,ny)&&maze[nx][ny]==maze[x][y])
17 {
18 if (!vis[nx][ny])
19 {
20 dfs(nx,ny,x,y);
21 }
22 else
23 {
24 flag = true;
25 return ;
26 }
27 }
28 }
1}
2int main()
3{
4 #ifndef ONLINE_JUDGE
5 freopen("code/in.txt","r",stdin);
6 #endif
1 scanf("%d %d",&n,&m);
2 for ( int i = 0 ; i < n ; i++) scanf("%s",maze[i]);
3 ms(vis,false);
4 flag = false;
5 for ( int i = 0 ; i < n ;i++)
6 {
7 if (flag) break;
8 for ( int j = 0 ; j < m ; j++)
9 {
10 if (flag) break;
11 if (!vis[i][j])
12 {
13 dfs(i,j,-1,-1);
14 }
15 }
16 }
17 if (flag)
18 {
19 puts("Yes");
20 }
21 else
22 {
23 puts("No");
24 }
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}