ZOJ 1148 The Game

题目地址:点击打开链接

思路:感觉有点坑,(1)题目的图片没有正确显示,看我粘的图(2)输入的时候先输入的是纵坐标,后输入的是横坐标(3)每个输出块后要打印一个空行(4)本来都把打印step数组的输出给括掉了,结果输出错误,后来直接删掉就A了,和普通的BFS不太一样,和连连看差不多,要少拐弯,因为拐的越多,步数越多,要尽量沿着一个方向一直搜,为了方便理解打印了一下step数组


AC代码:

#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>

using namespace std;

int step[80][80];
char map1[80][80];
int w,h,starti,startj,endi,endj;
int dir[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};

struct point
{
    int x,y;
}in,out;

bool check(int x,int y)
{
    if(x >= 0 && x <= h+1 && y >=0 && y <= w+1 && map1[x][y] != 'X' && step[x][y] == 0)
        return true;
    return false;
}

void bfs()
{
    int i;
    queue<point> q;
    in.x = starti;
    in.y = startj;
    map1[endi][endj] = ' ';
    q.push(in);
    while(!q.empty() && step[endi][endj] == 0)
    {
        out = q.front();
        q.pop();
        for(i=0; i<4; i++)
        {
            in.x = out.x + dir[i][0];
            in.y = out.y + dir[i][1];
            while(check(in.x,in.y) && step[endi][endj] == 0)
            {
                q.push(in);
                step[in.x][in.y] = step[out.x][out.y] + 1;//和它在一条线上的步数都是加1
                in.x += dir[i][0];
                in.y += dir[i][1];
            }
        }
    }
    map1[endi][endj] = 'X';
}

int main()
{
    int i,l = 1,m;
    while(scanf("%d%d",&w,&h))
    {
        if(w + h == 0)
            break;
        getchar();//读取回车,不然输入图的时候,第一行为空格
        memset(map1,' ',sizeof(map1));//在外围框一层空格
        for(i=1; i<=h; i++)
        {
            gets(&map1[i][1]);//用gets读入,getline会保留换行符,从1开始读入的,所以为map1[i][1]
        }
        printf("Board #%d:\n",l++);
        m = 1;
        while(scanf("%d%d%d%d",&startj,&starti,&endj,&endi))
        {
            if(starti + startj + endi + endj == 0)
                break;
            memset(step,0,sizeof(step));
            bfs();
            if(step[endi][endj] == 0)
                printf("Pair %d: impossible.\n",m++);
            else
                printf("Pair %d: %d segments.\n",m++,step[endi][endj]);
        }
        printf("\n");//Output a blank line after each board.
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值