题目网址
http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1416
简单的深搜
直接上代码
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#define ll long long
#define DEBUG print
using namespace std;
bool hash[51][51];
char tu[55][55];
int path[55][55];
bool dfs(int n,int m,int i,int j,int count,char c)
{
// DEBUG("%c %d %d\n",c,i,j);
hash[i][j]=0;
path[i][j]=count;
if(j+1<m&&tu[i][j+1]==c){
if(path[i][j+1]<0){
if(dfs(n,m,i,j+1,count+1,c))return true;
}
else {
if(path[i][j]-path[i][j+1]>=3)return true;
}
}
if(i+1<n&&tu[i+1][j]==c){
if(path[i+1][j]<0){
if(dfs(n,m,i+1,j,count+1,c))return true;
}
else {
if(path[i][j]-path[i+1][j]>=3)return true;
}
}
if(j-1>=0&&tu[i][j-1]==c){
if(path[i][j-1]<0){
if(dfs(n,m,i,j-1,count+1,c))return true;
}
else {
if(path[i][j]-path[i][j-1]>=3)return true;
}
}
if(i-1>=0&&tu[i-1][j]==c){
if(path[i-1][j]<0){
if(dfs(n,m,i-1,j,count+1,c))return true;
}
else {
if(path[i][j]-path[i-1][j]>=3)return true;
}
}
return false;
}
int main()
{
// memset(hash,1,sizeof(hash));
memset(tu,0,sizeof(tu));
// memset(path,-1,sizeof(path));
int n,m;
scanf("%d%d",&n,&m);
getchar();
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
hash[i][j]=1;
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
path[i][j]=-1;
}
}
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
scanf("%c",&tu[i][j]);
}
getchar();
}
bool ansflag=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(!hash[i][j])continue;
else {
if(dfs(n,m,i,j,0,tu[i][j])){
ansflag=1;
break;
}
}
}
if(ansflag)break;
}
if(ansflag)printf("Yes\n");
else printf("No\n");
}