传送:https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1416
题意:判断地图内同一种类字符是否有成环的,是则输出YES,否则NO。
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#define maxn 55
#define lson step<<1
#define rson step<<1|1
using namespace std;
int n,m,bj;
char mapp[maxn][maxn];
bool book[maxn][maxn];
void inputmap(){
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>mapp[i][j];
}
}
}
bool check(int x,int y,int xx,int yy)
{
int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int tx,ty;
for(int i=0;i<4;i++)
{
tx=x+next[i][0];
ty=y+next[i][1];
if(tx==xx&&ty==yy)
return true;
}
return false;
}
void dfs(int x,int y,int xx,int yy,int step){
int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};
int tx,ty;
if(bj==1)
return ;
if(check(x,y,xx,yy)&&step>=4)
{
bj=1;
return ;
}
for(int i=0;i<4;i++)
{
tx=x+next[i][0];
ty=y+next[i][1];
if(mapp[tx][ty]!=mapp[x][y])
{
continue;
}
if(book[tx][ty]==false)
{
book[tx][ty]=true;
dfs(tx,ty,xx,yy,step+1);
book[tx][ty]=false;
}
}
return ;
}
int main()
{
while(cin>>n>>m)
{
inputmap();
int flag=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
memset(book,false,sizeof(false));
book[i][j]=true;
bj=0;
dfs(i,j,i,j,1);
if(bj==1)
{
flag=1;
break;
}
}
if(flag)
break;
}
if(flag)
cout << "Yes\n";
else
cout << "No\n";
}
return 0;
}