Three-dimensional Sokoban (bfs)

Three-dimensional Sokoban

Insert picture description here

Insert picture description here

Problem solving ideas

This is a problem when bfs
analog cuboid various states of
the amount of code a big point of it

AC code

#include<cstdio>
#include<cstring>
using namespace std;
int n,m,x1,y1,px[2500005],py[2500005],pt[2500005],ps[2500005],a[505][505],c[505][505][5];
int dx[4][4]={
    
    {
    
    },{
    
    -1,0,2,0},{
    
    -1,0,1,0},{
    
    -2,0,1,0}};//几种移动
int dy[4][4]={
    
    {
    
    },{
    
    0,2,0,-1},{
    
    0,1,0,-2},{
    
    0,1,0,-1}};
int dt[4][4]={
    
    {
    
    },{
    
    3,2,3,2},{
    
    2,1,2,1},{
    
    1,3,1,3}};
bool check(int x,int y,int t)//判断
{
    
    
	if(x<1||x>n||y<1||y>m)return false;
	if(t==1)
	{
    
    
		if(a[x][y]=='E')return false;
		if(a[x][y]=='#')return false;
	}
	if(t==2)
	{
    
    
		if(a[x][y]=='#')return false;
		if(a[x][y-1]=='#')return false;
	}
	if(t==3)
	{
    
    
		if(a[x][y]=='#')return false;
		if(a[x-1][y]=='#')return false;
	}
	if(c[x][y][t]==1)return false;
	return true; 
}
void bfs()//bfs
{
    
    
	int head=0,tail=1;
	while(head<tail)
	{
    
    
		head++;
		for(int i=0;i<4;i++)
		{
    
    
			int x=px[head]+dx[pt[head]][i],y=py[head]+dy[pt[head]][i],t=dt[pt[head]][i];
			if(check(x,y,t))
			{
    
    
				c[x][y][t]=1;
				px[++tail]=x;
				py[tail]=y;
				pt[tail]=t;
				ps[tail]=ps[head]+1;
				if(x==x1&&y==y1&&t==1)
				{
    
    
					printf("%d\n",ps[tail]);
					return;
				}
			}
		}
	}
	printf("Impossible\n");
	return;
}
int main()
{
    
    
	while(scanf("%d%d",&n,&m))
	{
    
    
		if(n==0&&m==0)return 0;
		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]!='X'&&a[i][j]!='E'&&a[i][j]!='O')
			 a[i][j]=getchar();
		 }
		memset(c,0,sizeof(c));//预处理,找起点和终点
		for(int i=1;i<=n;i++)
		 for(int j=1;j<=m;j++)
		 {
    
    
			if(a[i][j]=='X')
			{
    
    
				px[1]=i;py[1]=j;ps[1]=0;
				if(a[i][j-1]=='X')pt[1]=2;
				else if(a[i-1][j]=='X')pt[1]=3;
				else pt[1]=1;
				c[i][j][pt[1]]=1;
			}
			if(a[i][j]=='O')
			{
    
    
				x1=i;
				y1=j;
			}	
	     }
	    bfs();
	}
	return 0;
}

Thank you

Guess you like

Origin blog.csdn.net/weixin_45524309/article/details/112973700