POJ1101 二维图BFS

POJ1101 二维图BFS

参考博文

https://blog.csdn.net/weixin_33786077/article/details/94190005

https://blog.csdn.net/weixin_40953222/article/details/80544928

题目分析

连连看,问你最少能拐几个弯

这道题全部参考博客的代码及思想,感觉很巧妙,代码也很精巧

核心:对于每个点,一般的广搜方法是对与其直接相连的每个点进行搜索,记录下上次的方向之后与这次的方向进行对比,更新转向次数;这里的广搜则是对其上下左右的一条射线上的每个点进行搜索,换句话说射线上的每个点都视为同一层,因为已经访问过的点不会再次访问,所以每一层都是一次拐弯

应该注意的细节是,终点在搜索开始前应该设置为空格;题目中的坐标系与矩阵的表示方式相冲突,在处理时把题目中的坐标系xy对调即可

代码

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

int w,h,x1,y1,x2,y2,CNT = 0,cnt;
int dirx[]={1,-1,0,0},diry[]={0,0,1,-1},vis[99][99];
char a[99][99];

bool check(int x,int y){
    return (x<=h+1&&x>=0&&y<=w+1&&y>=0 && a[x][y]!='X' && !vis[x][y]);
}

int bfs(int x, int y){
    queue<int> aa,bb;
    aa.push(x);bb.push(y);

    while(!aa.empty()){
        int tmpa = aa.front(),tmpb = bb.front();
        aa.pop();bb.pop();
        if(tmpa==x2&&tmpb==y2) return vis[tmpa][tmpb];
        for(int i = 0;i <= 3;i++){
            int tempa = tmpa,tempb = tmpb;
            while(check(tempa+dirx[i],tempb+diry[i])){
                tempa+=dirx[i];tempb+=diry[i];
                vis[tempa][tempb] = vis[tmpa][tmpb]+1;
                aa.push(tempa);bb.push(tempb);
            }
        }
    }
    return -1;
}

int main(){
    while(scanf("%d%d",&w,&h)&&w){
        memset(a,0,sizeof(a));
        CNT++;
        cnt = 0;
        printf("Board #%d:\n",CNT);
        for(int i = 1;i <= h;i++)
            for(int j = 0;j <= w;j++)
                scanf("%c",&a[i][j]);//注意会读入换行符
        while(scanf("%d%d%d%d",&y1,&x1,&y2,&x2)&&x1){
            cnt++;
            memset(vis,0,sizeof(vis));
            a[x2][y2] = ' ';
            int ttt=bfs(x1,y1);
            if(ttt!=-1) printf("Pair %d: %d segments.\n",cnt,ttt);
            else printf("Pair %d: impossible.\n",cnt);
            a[x2][y2] = 'X';
        }
        printf("\n");
    }
}

567K 16MS

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值