题意:
有一1*2大小的木块(直立时可看作是1*1)在n*m的矩形上滚动,求到达目的(只能是直立的)最小步骤;
其中 *代表木板,#代表空地,X代表初始位置,E代表有损坏的木板(不能直立在上面),O代表目的地;刚
开始是木块可以直立或竖放;
想法:
刚开始是认为只有两种状态,一直wrong,看了别人的才知道想错了,是3中状态(直立,横放,竖放),则
找到Move[3][4][3]= (状态,移动步骤,到下一状态的移动),横放时记录左面的点,竖放时记录上面的点;
{
{ {0,-2,1},{0,1,1},{-2,0,2},{1,0,2} },
{ {0,-1,-1},{0,2,-1},{-1,0,0},{1,0,0} },
{ {0,-1,0},{0,1,0},{-1,0,-2},{2,0,-2} },
};
代码实现:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int MAX=506;
char Map[MAX][MAX];
bool Visted[MAX][MAX][3];
int n,m;
int Move[3][4][3]={
{{0,-2,1},{0,1,1},{-2,0,2},{1,0,2}},
{{0,-1,-1},{0,2,-1},{-1,0,0},{1,0,0}},
{{0,-1,0},{0,1,0},{-1,0,-2},{2,0,-2}},
};
struct Node
{
int x,y;
int step,dir;
};
queue<Node> Q;
void BFS( Node p1 )
{
while( !Q.empty() )
Q.pop();
memset(Visted,0,sizeof(Visted));
Visted[p1.x][p1.y][p1.dir]=1;
Q.push(p1);
while( !Q.empty() )
{
Node Now=Q.front();
Q.pop();
for( int i=0; i<4; ++i )
{
Node Next;
Next.x=Now.x+Move[Now.dir][i][0];
Next.y=Now.y+Move[Now.dir][i][1];
Next.dir=Now.dir+Move[Now.dir][i][2];
Next.step=Now.step+1;
if( Next.dir==0 )
{
if( Next.x<0 || Next.y<0 || Next.x>=n || Next.y>=m
|| Map[Next.x][Next.y]=='E' || Map[Next.x][Next.y]=='#' )
continue;
}
else if( Next.dir==1 )
{
if( Next.x<0 || Next.y<0 || Next.x>=n || Next.y+1>=m
|| Map[Next.x][Next.y]=='#' || Map[Next.x][Next.y+1]=='#' )
continue;
}
else{
if( Next.x<0 || Next.y<0 || Next.x+1>=n || Next.y>=m
|| Map[Next.x][Next.y]=='#' || Map[Next.x+1][Next.y]=='#' )
continue;
}
if( !Visted[Next.x][Next.y][Next.dir] )
{
Visted[Next.x][Next.y][Next.dir]=1;
if( Map[Next.x][Next.y]=='O' && Next.dir==0 )
{
printf("%d\n",Next.step);
return;
}
Q.push(Next);
}
}
}
printf("Impossible\n");
}
int main()
{
// freopen("in.txt","r",stdin);
int x1,y1,x2,y2,k;
while( scanf("%d%d",&n,&m)!=EOF )
{
if( !n && !m )
break;
x1=x2=y1=y2=k=0;
getchar();
for( int i=0; i<n; ++i )
{
for( int j=0; j<m; ++j )
{
scanf("%c",&Map[i][j]);
if( Map[i][j]=='X' )
{
if( k==0 )
{
x1=i;
y1=j;
k++;
}
else{
x2=i;
y2=j;
k++;
}
}
}
getchar();
}
Node p1;
p1.x=x1;
p1.y=y1;
int p=-1;
if( k==1 )
{
p=0;
}
else
{
if( x1==x2 )
p=1;
else
p=2;
}
p1.dir=p;
p1.step=0;
BFS(p1);
}
return 0;
}