[Ybtoj 1.5 high-efficiency advanced] C. Three-dimensional stacking of boxes [Guang search]

Insert picture description here
Insert picture description here

analysis

Record the three positions of the cuboid. When
standing up, only record itself, record the bottom one vertically, and record the one on the right side horizontally,
and then figure out which states are in the three situations.
Run the classic wide search and
record the number of steps.

Upload code

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
struct lwx
{
    
    
	int x,y,t,b;
}q[1000001];
char c;
int n,m,h,t,ex,ey,a[501][501],v[501][501][5];
int dx[4][5]={
    
    {
    
    },{
    
    0,-1,0,2,0},{
    
    0,-2,0,1,0},{
    
    0,-1,0,1,0}};  
int dy[4][5]={
    
    {
    
    },{
    
    0,0,2,0,-1},{
    
    0,0,1,0,-1},{
    
    0,0,1,0,-2}};  //坐标的变化
int dt[4][5]={
    
    {
    
    },{
    
    0,2,3,2,3},{
    
    0,1,2,1,2},{
    
    0,3,1,3,1}};  //状态的变化
bool pd(int xx,int yy,int tt)
{
    
    
	if(xx<1||xx>n||yy<1||yy>m) return 0;
	if(tt==1&&a[xx][yy]==0) return 1;
	if(tt==2&&a[xx][yy]!=1&&a[xx-1][yy]!=1&&xx-1>0) return 1;
	if(tt==3&&a[xx][yy]!=1&&a[xx][yy-1]!=1&&yy-1>0) return 1;
	return 0;
}
int bfs()
{
    
    
	while(h<t)
	{
    
    
		h++;
		for(int i=1;i<=4;i++)
		{
    
    
			int xx=q[h].x+dx[q[h].t][i];
			int yy=q[h].y+dy[q[h].t][i];
			int tt=dt[q[h].t][i];
			if(pd(xx,yy,tt)&&!v[xx][yy][tt])
			{
    
    
				t++;
				q[t].x=xx;
				q[t].y=yy;
				q[t].t=tt;
				q[t].b=q[h].b+1;
				v[xx][yy][tt]=1;
				if(xx==ex&&yy==ey&&q[t].t==1)
				{
    
    
					cout<<q[t].b<<endl;
					return 0;
				}
			}
		}
	}
	return 1;
}
int main()
{
    
    
	while(1)
	{
    
    
		cin>>n>>m;
		if(!n&&!m) break;
		h=0;t=1;
		int vis=0;
		memset(a,0,sizeof(a));
		memset(q,0,sizeof(q));
		memset(v,0,sizeof(v));
		q[t].t=1;
		for(int i=1;i<=n;i++)
		{
    
    
			for(int j=1;j<=m;j++)
			{
    
    
				cin>>c;
				if(c=='#') a[i][j]=1;
			    if(c=='E') a[i][j]=-1;
			    if(c=='O') ex=i,ey=j,a[i][j]=0;
			    if(c=='X')
			    {
    
    
			    	if(vis)
			    	{
    
    
			    		if(q[t].x+1==i&&q[t].x)
			    		{
    
    
			    			q[t].t=2;
						}
						else q[t].t=3;
					}
					q[t].x=i;
					q[t].y=j;
					vis=1;
				}
			}
		}
		v[q[t].x][q[t].y][q[t].t]=1;
		if(bfs()) cout<<"Impossible"<<endl;
	}
	return 0;
} 

Guess you like

Origin blog.csdn.net/dglyr/article/details/113003147