推箱子(广搜)

题目:

时限:1000ms 内存限制:10000K  总时限:3000ms

描述

绝大多数人都玩过推箱子的游戏,控制一个人将箱子推动到目标位置即获得胜利。现请你编写一个程序,判断将箱子推到目标位置至少需要多少步。

输入

推箱子的平面区域为固定大小(10*10),使用10行10列输入推箱子的初始局面。其中,0代表空格,1代表墙,2代表箱子,3代表目标位置,4代表人。
注:游戏中只有一个箱子,一个目标位置,一个人。

输出

输出将箱子推到目标位置的最小步数;若箱子不可能被推到目标位置,输出-1。

输入样例

0000000000
0000000300
0100000000
0100000000
0101111100
0000010000
0000010000
0020010040
0000010000
0000010000

输出样例

34

提示

思路:

其实和原来的广搜还是一样的,就是人走的时候需要先找到箱子,找到箱子之后在去找目的地,结构体里边定义人和箱子的坐标,这样看起来整齐。箱子解释见代码

#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string.h>
#include <queue>
using namespace std;

const int maxn = 15;

struct MAN
{
    int x;
    int y;
    int box_x;
    int box_y;
    int step;
};

char maze[maxn][maxn];
int dir[4][2] = {1,0,0,1,-1,0,0,-1};
bool hush[maxn][maxn][maxn][maxn];//用来判断该位置是否访问过 

int bfs(MAN st)
{
    memset(hush,false,sizeof hush);
    queue<MAN>man;
    st.step = 0;
    man.push(st);
    MAN now,next;
    hush[st.x][st.y][st.box_x][st.box_y] = 1;
    while(!man.empty())
    {
        now = man.front();
        man.pop();
        if(maze[now.box_x][now.box_y] == '3')
            return now.step;
        for(int i = 0;i <4;i ++)
        {
            next.x = now.x + dir[i][0];
            next.y = now.y + dir[i][1];
            next.step = now.step + 1;//以上三行是人走的 
            next.box_x = now.box_x;
            next.box_y = now.box_y;
            if(next.x < 0 || next.x >= 10 || next.y < 0 || next.y >= 10)//越界 
                continue;
            if(maze[next.x][next.y] == '1')//墙 
                continue;
            if(hush[next.x][next.y][now.box_x][now.box_y])//访问过 
                continue;
            if(next.x == now.box_x && next.y == now.box_y)//遇到箱子,那就推吧 
            {
                next.box_x = now.box_x + dir[i][0];
                next.box_y = now.box_y + dir[i][1];//以上两行是箱子的行走 
                if(maze[next.box_x][next.box_y] == '1')// 墙 
                    continue;
                if(next.box_x < 0 || next.box_y < 0 || next.box_x >=10 || next.box_y >= 10)//越界 
                    continue;
                if(hush[next.x][next.y][next.box_x][next.box_y])//访问过 
                    continue;
            }
            hush[next.x][next.y][next.box_x][next.box_y] = 1;
            man.push(next);
        }
    }
    return -1;
}

int main()
{
    MAN st;
    for(int i = 0;i < 10;i ++)
    {
        cin >> maze[i];
    }
    for(int i = 0;i < 10;i ++)
        for(int j = 0;j < 10;j ++)
    {
        if(maze[i][j] == '2')
            st.box_x = i,st.box_y = j;
        if(maze[i][j] == '4')
            st.x = i,st.y = j;
    }
    int step = bfs(st);
    cout << step << endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值