poj 1101 The Game

这个题,discuss里说可能数据比较水,我用了普遍认为正确的一个方向一直搜下去,用队列和优先队列都可以,没有区别。

#include <iostream>
#include"stdio.h"
#include"string.h"
#include"queue"
using namespace std;
const int maxn = 100 + 5;
int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}};
int w,h;
bool vst[maxn][maxn];
char game[maxn][maxn];
struct node
{
    int step;
    int x,y;
    bool friend operator <(node a,node b)
    {
       return a.step > b.step;
    }
};

int BFS(int sx,int sy,int ex,int ey)
{
    memset(vst,0,sizeof(vst));
    queue<node> q;
    node cur,next;
    cur.step = 0;
    cur.x = sx;
    cur.y = sy;
    vst[cur.x][cur.y] = true;
    q.push(cur);
    while(!q.empty())
    {
        cur = q.front();
        if(cur.x == ex && cur.y == ey)
            return cur.step;
        q.pop();
        for(int i=0;i<4;i++)
        {
            next.x = cur.x + dir[i][0];
            next.y = cur.y + dir[i][1];
            while(next.x>=0 && next.x<=h+1 && next.y >=0 && next.y<=w+1 && !vst[next.x][next.y] && game[next.x][next.y]==' ')
            {
                vst[next.x][next.y] = true;
                next.step = cur.step + 1;
                q.push(next);
                next.x += dir[i][0];
                next.y += dir[i][1];
            }
        }
    }
    return -1;

}

int main()
{
    int CNT = 1;
    while(scanf("%d%d",&w,&h)!=EOF&&(w||h))
    {
        memset(game,' ',sizeof(game));
        for(int i=1;i<=h;i++)
        {
            getchar();
            for(int j=1;j<=w;j++)
                game[i][j] = getchar();
        }
        printf("Board #%d:\n",CNT++);
        int sx,sy,ex,ey;
        int cnt=1;
        while(scanf("%d%d%d%d",&sy,&sx,&ey,&ex)!=EOF&&(ex||ey||sx||sy))
        {
            printf("Pair %d: ",cnt++);
            game[ex][ey] = ' ';
            int ans = BFS(sx,sy,ex,ey);
            if(ans == -1)
                printf("impossible.\n");
            else
                printf("%d segments.\n",ans);
            game[ex][ey] = 'X';
        }
       printf("\n");
    }
    return 0;
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值