HDU 1175 连连看 dfs

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;

int n,m;
int graph[1005][1005];
bool vis[1005][1005];
int x1,y1,x2,y2;
bool flag;

void dfs(int x,int y,int dir,int turn){   //1 2 3 4 上下左右
    if(flag) return;
    if(turn==3) return;
    if(x<=0 || y<=0 || x>n || y>m) return;
    if(x==x2 && y==y2){
        flag = true;
        return ;
    }
    if(turn==2){  //若当前已经达到最大的转弯次数,而到达终点仍然需要转弯
        if(!((dir==1 && y==y2 && x>x2) || (dir=2 && y==y2 && x<x2) || (dir==3 && x==x2 && y>y2) || (dir==4 && x==x2 && y<y2) ))
            return;
    }
    if(graph[x][y]!=0) return; //此处非空,不能经过
    if(vis[x][y]) return;
    vis[x][y] = 1;
    if(dir==1){
        dfs(x-1,y,1,turn);
        dfs(x+1,y,2,turn+1);
        dfs(x,y-1,3,turn+1);
        dfs(x,y+1,4,turn+1);
    }
    else if(dir==2){
        dfs(x-1,y,1,turn+1);
        dfs(x+1,y,2,turn);
        dfs(x,y-1,3,turn+1);
        dfs(x,y+1,4,turn+1);
    }
    else if(dir==3){
        dfs(x-1,y,1,turn+1);
        dfs(x+1,y,2,turn+1);
        dfs(x,y-1,3,turn);
        dfs(x,y+1,4,turn+1);
    }
    else if(dir==4){
        dfs(x-1,y,1,turn+1);
        dfs(x+1,y,2,turn+1);
        dfs(x,y-1,3,turn+1);
        dfs(x,y+1,4,turn);
    }
    vis[x][y] = 0;  //回溯
}

int main(){
    while(scanf("%d%d",&n,&m)){
        if(n==0 && m==0) break;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                scanf("%d",&graph[i][j]);
            }
        }
        int q;
        scanf("%d",&q);
        while(q--){
            memset(vis,false,sizeof(vis));  //每次查询都需要重置
            scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
            if(x1==x2 && y1==y2 && graph[x1][y1]!=0)
                printf("NO\n");
            else if(graph[x1][y1]==graph[x2][y2] && graph[x1][y1]!=0){
                flag = 0;
                dfs(x1-1,y1,1,0);
                dfs(x1+1,y1,2,0);
                dfs(x1,y1-1,3,0);
                dfs(x1,y1+1,4,0);
                if(flag)
                    printf("YES\n");
                else
                    printf("NO\n");
            }
            else
                printf("NO\n");
        }
    }
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值