codeforces 510 B. Fox And Two Dots

http://codeforces.com/contest/510/problem/B 题意:给定一个maze,用不同的字母代表不同的颜色。问能否找到一个颜色相同的环(失少四个点组成) 思路:dfs一遍,如果遇到之前已经访问过的点,说明成环。需要注意的是,要注意由一个点向某方向移动,然后由反方向移动到该点所造成的误判。所以dfs除了要知道当前的坐标x,y,还要记录之前的坐标px,py.

  1/* ***********************************************
  2Author :111qqz
  3Created Time :2015年12月05日 星期六 21时35分07秒
  4File Name :code/cf/problem/510B.cpp
  5************************************************ */
  6
  7#include <cstdio>
  8#include <cstring>
  9#include <iostream>
 10#include <algorithm>
 11#include <vector>
 12#include <queue>
 13#include <set>
 14#include <map>
 15#include <string>
 16#include <cmath>
 17#include <cstdlib>
 18#include <ctime>
 19#define fst first
 20#define sec second
 21#define lson l,m,rt<<1
 22#define rson m+1,r,rt<<1|1
 23#define ms(a,x) memset(a,x,sizeof(a))
 24typedef long long LL;
 25
 26
 27
 28using namespace std;
 29const double eps = 1E-8;
 30const int dx4[4]={1,0,0,-1};
 31const int dy4[4]={0,-1,1,0};
 32const int inf = 0x3f3f3f3f;
 33const int N=55;
 34int n,m;
 35char maze[N][N];
 36bool vis[N][N];
 37bool flag;
 38
 39
 40bool inmaze( int x,int y)
 41{
 42    if (x>=0&&x<n&&y>=0&&y<m) return true;
 43    return false;
 44}
 45void dfs( int x,int y,int px,int py)  //要记录当前的x,y是由哪里来的。把因为由px,py到x,y再回到px,py引起的误判剔除。
 46{					//判cycle方式为:到达一个之前已经到达过的点。
 47    vis[x][y] = true;
 48   // cout<<"x:"<<x<<" y:"<<y<<" cur:"<<cur<<endl;
 49    if (flag) return;
 50    for ( int i = 0 ; i < 4 ; i++)
 51    {
 52	int nx = x + dx4[i] ; 
 53	int ny = y + dy4[i] ;
 54	if (nx==px&&ny==py) continue;
 55	if (inmaze(nx,ny)&&maze[nx][ny]==maze[x][y])
 56	{
 57	    if (!vis[nx][ny])
 58	    {
 59		dfs(nx,ny,x,y);
 60	    }
 61	    else
 62	    {
 63		flag = true;
 64		return ;
 65	    }
 66	}
 67    }
 68
 69}
 70int main()
 71{
 72	#ifndef  ONLINE_JUDGE 
 73	freopen("code/in.txt","r",stdin);
 74  #endif
 75
 76	scanf("%d %d",&n,&m);
 77	for ( int i = 0 ; i < n ; i++) scanf("%s",maze[i]);
 78	ms(vis,false);
 79	flag = false;
 80	for ( int i = 0 ; i < n ;i++)
 81	{
 82	    if (flag) break;
 83	    for ( int j = 0 ; j < m ; j++)
 84	    {
 85		if (flag) break;
 86		if (!vis[i][j])
 87		{
 88		    dfs(i,j,-1,-1);
 89		}
 90	    }
 91	}
 92	if (flag)
 93	{
 94	    puts("Yes");
 95	}
 96	else
 97	{
 98	    puts("No");
 99	}
100
101  #ifndef ONLINE_JUDGE  
102  fclose(stdin);
103  #endif
104    return 0;
105}