HDU 1175 广度优先搜索(BFS)

http://acm.hdu.edu.cn/showproblem.php?pid=1175

:能不能将两个位置的棋子(非0)消去,并不能超过两次改变方向.

型:广度优先搜索(BFS)

思路:将其中的一个点作为起点,向外搜索,看能否在限制条件之内找到另一个点

个人总结:我做的时候没考虑完全,所以没有用数组(代码中的num)保存到达该点时转向最少次数,所以一直WA了!


#include<iostream>
#include<string>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cctype>
#include<iomanip>
#include<queue>

using namespace std;
const int inf=10000000;

struct node{
    int x,y;
    int d;
    int k;
}st,rt,ne;

int n,m;
int map[1005][1005];
int num[1005][1005];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};

bool BFS(int x1,int y1,int x2,int y2){
    if(map[x1][y1]!=map[x2][y2]||!map[x1][y1])return false;
    for(int i=1;i<=n;++i)
        for(int j=1;j<=m;++j)
            num[i][j]=1000;
    queue<node>M;
    st.x=x1, st.y=y1, st.k=0, st.d=-1;
    num[x1][y1]=0;
    M.push(st);
    while(!M.empty()){
        rt=M.front(); M.pop();
        for(int i=0;i<4;++i){
            ne=rt;
            ne.x+=dx[i];
            ne.y+=dy[i];
            if(ne.x<=0||ne.y<=0||ne.x>n||ne.y>m)continue;
            if(ne.d!=i)ne.k++;
            ne.d=i; ///转向一次
            if(ne.k>3)continue;       ///超地两次转向
            if(ne.x==x2&&ne.y==y2)return true;///能找到目标点
            if(map[ne.x][ne.y])continue;//cout<<ne.x<<' '<<ne.y<<' '<<ne.k<<endl;
            if(ne.k<num[ne.x][ne.y]){
                num[ne.x][ne.y]=ne.k;
                M.push(ne);
            }
        }
    }
    return false;
}

int main(){
    while(~scanf("%d%d",&n,&m)&&(n||m)){
        for(int i=1;i<=n;++i)
            for(int j=1;j<=m;++j)
                scanf("%d",&map[i][j]);
        int q; scanf("%d",&q);
        while(q--){
            int x1,y1,x2,y2;
            scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
            if(BFS(x1,y1,x2,y2))puts("YES");
            else puts("NO");
        }
    }
    return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值