51nod 1416两点DFS

题目网址

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");
 } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值