172. 立体推箱子

传送门

此题是一道比较明显但又麻烦的广搜题,经典的走迷宫求最少步骤的题

由于这个题的状态有些麻烦,我们建立一个三元组结构体 ( x , y , l i e ) (x,y,lie) (x,y,lie), x , y x,y x,y表示坐标, l i e lie lie表示现在是立着的还是横着躺或是竖着躺

l i e = 0 lie=0 lie=0,表示立着,且坐标为 x , y x,y x,y
l i e = 1 lie=1 lie=1,表示横着躺,且左半部分为 x , y x,y x,y
l i e = 2 lie=2 lie=2,表示竖着躺,且上半部分为 x , y x,y x,y

预先处理出nex

int next_x[3][4]={{ 0,0,-2,1},{ 0,0,-1, 1},{ 0, 0,-1, 2}};
int next_y[3][4]={{-2,1, 0,0},{-1,2, 0, 0},{-1, 1, 0, 0}};
int next_lie[3][4]={{1,1,2,2},{0,0,1,1},{2,2,0,0}};

3 3 3种状态, 4 4 4个滚动方向
建议在做这个预处理的时候可以实物模拟一下,4399小游戏里有
模拟链接

Code

#include<bits/stdc++.h>
#include<queue>
#define rep(i,a,b) for(int (i)=(a);(i)<=(b);(i)++)
using namespace std;
const int maxn=1e6+10;
const int maxm=1000+10;
int m,n,ans;
char s[maxm][maxm];
int dis[maxm][maxm][4];

struct node{
	int x,y,lie;
};
queue<node> q;
node start,en;

int next_x[3][4]={{ 0,0,-2,1},{ 0,0,-1, 1},{ 0, 0,-1, 2}};
int next_y[3][4]={{-2,1, 0,0},{-1,2, 0, 0},{-1, 1, 0, 0}};
int next_lie[3][4]={{1,1,2,2},{0,0,1,1},{2,2,0,0}};

bool check(node nex) {
	if(nex.x <1 || nex.y<1 || nex.x>n || nex.y>m) return false;
	if(s[nex.x][nex.y]=='#') return false;
	if(nex.lie==0 && s[nex.x][nex.y]!='.') return false;
	if(nex.lie==1 && s[nex.x][nex.y+1]=='#') return false;
	if(nex.lie==2 && s[nex.x+1][nex.y]=='#') return false;
	return true;
}

int bfs() {
	memset(dis,-1,sizeof(dis));
	while(q.size()) q.pop();
	dis[start.x][start.y][start.lie]=0;
	q.push(start);
	while(q.size()) {
		node now=q.front();q.pop();
		rep(i,0,3) {
			node nex;
			nex.x=now.x+next_x[now.lie][i];
			nex.y=now.y+next_y[now.lie][i];
			nex.lie=next_lie[now.lie][i];
			if(check(nex)==0) continue;
			if(dis[nex.x][nex.y][nex.lie]==-1) {
				dis[nex.x][nex.y][nex.lie]=dis[now.x][now.y][now.lie]+1;
				q.push(nex);
				if(nex.x==en.x && nex.y==en.y && nex.lie==en.lie) 
				return dis[nex.x][nex.y][nex.lie];
			}
		}
	}
	return -1;
}

void readdata() {
	while(1) {
		memset(s,false,sizeof(s));
		memset(dis,false,sizeof(dis));
		while(q.size()) q.pop();
		scanf("%d%d",&n,&m);
		if(m==0 && n==0) break;
		ans=0;
		rep(i,1,n) scanf("%s",s[i]+1);
		start={-1},en;
		rep(i,1,n) {
			rep(j,1,m) {
				if(s[i][j]=='O') en={i,j,0};
				if(s[i][j]=='X' && start.x==-1) {
					if(s[i][j+1]=='X') start={i,j,1};
					else if(s[i+1][j]=='X') start={i,j,2};
					else start={i,j,0};
				}
			}
		}
		s[start.x][start.y]=s[en.x][en.y]='.';
		int ans=bfs();
		if(ans==-1) printf("Impossible\n");
		else printf("%d\n",ans);
	}
}

int main() {
	freopen("input.txt","r",stdin);
	readdata();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值