YbtOJ——广度搜索【例题3】立体推箱子

C. 【例题3】立体推箱子

题目

在这里插入图片描述

题解

求最少步数,当然用广搜。
队列里记录当前这一步的三个状态,分别是:坐标(x,y)和箱子状态( t )。
其中箱子的状态有三种:立着,横躺着,竖躺着。分别用0,1,2表示。
箱子横着躺或竖着躺占两个格子,对于横躺,将其坐标记作右边的格子;对于竖躺,坐标记作下面的格子。
再加些处理(程序注释里有解释)便可把这个复杂的游戏变成简单的广搜走迷宫了~

代码

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<queue>
using namespace std;
int sx,sy,st,ex,ey,n,m,a[510][510],d[510][510][3];
//dx,dy,dt记录x,y,t在不同状态下往不同方向走的变化
int dx[3][4]=
{
	{0,2,0,-1},
	{0,1,0,-1},
	{0,1,0,-2}
};
int dy[3][4]=
{
	{2,0,-1,0},
	{1,0,-2,0},
	{1,0,-1,0}
};
int dt[3][4]=
{
	{1,2,1,2},
	{0,1,0,1},
	{2,0,2,0}
};
bool f[510][510][3];
struct node
{
	int x,y,t;
};
bool check(int x,int y,int t)//检查这一步走得符不符合规则
{
	if(x<1||y<1||x>n||y>m||a[x][y]=='#') return 0;
	if(t==0&&a[x][y]=='E') return 0;
	if(t==1&& (y-1<1||a[x][y-1]=='#')) return 0;
	if(t==2&& (x-1<1||a[x-1][y]=='#')) return 0;
	return 1;
}
void bfs()
{
	f[sx][sy][st]=1;
	queue<node> q;
	q.push(node {sx,sy,st});
	do
	{
		node j=q.front();
		int x=j.x,y=j.y,t=j.t;
		q.pop();
		if(x==ex&&y==ey&&t==0)//找到答案就直接输出并退出
		{
			cout<<d[x][y][t]<<endl;
			return;
		}
		for(int i=0; i<4; i++)
		{
			int xx=x+dx[t][i],yy=y+dy[t][i],tt=dt[t][i];
			if(check(xx,yy,tt)&&!f[xx][yy][tt])
			{
				d[xx][yy][tt]=d[x][y][t]+1;
				f[xx][yy][tt]=1;  //标记此状态已访问过
				q.push(node {xx,yy,tt});
			}
		}
	}
	while(!q.empty());
	cout<<"Impossible"<<endl;
}
void in()
{
	st=0;//记得初始化起点状态!!!!(我就是这样错的)
	cin>>n>>m;
	for(int i=1; i<=n; i++)
	{
		for(int j=1; j<=m; j++)
		{
			a[i][j]=getchar();
			//读入到有效信息为止
			while(a[i][j]!='#'&&a[i][j]!='.'&&a[i][j]!='E'&&a[i][j]!='X'&&a[i][j]!='O')
			a[i][j]=getchar();
			if(a[i][j]=='X')//处理起点信息
			{
				sx=i;
				sy=j;
				if(a[i][j-1]=='X') st=1;
				if(a[i-1][j]=='X') st=2;
			}
			if(a[i][j]=='O')
			{
				ex=i;
				ey=j;
			}
		}
	}
}
bool work()
{
	in();
	if(!n&&!m) return 0;
	bfs();
	return 1;
}
int main()
{
	while((work()))
	{
		memset(f,0,sizeof(f));
		memset(d,0,sizeof(d));
		//初始化,因为有多测
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值