
3 7 ... ... .b. ... ... .a. ...
4 1 UDUHintHint: The following figures show the sample. The circle is the position of the pusher. And the squares are blocks (The two nested squares indicating a pile of two blocks). And this is the unique solution for this case.
#include<stdio.h>
#include<iostream>
#include<queue>
using namespace std;
struct node
{
int sx,sy;
int x,y,n,blocksNumb;
char path[200];
char map[25][25];
};
char map[27][27];
int R,C,dir[4][2]={-1,0,1,0,0,-1,0,1};
char dirChar[4]={'U','D','L','R'};
int judge(node &tp,int e)
{
tp.path[tp.n]=dirChar[e];
tp.path[tp.n+1]='\0';
tp.n++;
tp.x=tp.x+dir[e][0];
tp.y=tp.y+dir[e][1];
if(tp.map[tp.x][tp.y]!='.')
return 0;
while(true)
{
tp.x=tp.x+dir[e][0];
tp.y=tp.y+dir[e][1];
if(tp.x<0||tp.x>=R||tp.y<0||tp.y>=C)
return 0;
if(tp.map[tp.x][tp.y]!='.')
{
if(tp.map[tp.x][tp.y]>'a')
{
tp.map[tp.x][tp.y]-=1;
tp.blocksNumb--;
int x=tp.x+dir[e][0];
int y=tp.y+dir[e][1];
if(x>=0&&x<R&&y>=0&&y<C)
{
if(tp.map[x][y]=='.')
tp.map[x][y]=tp.map[tp.x][tp.y];
else
tp.map[x][y]+=tp.map[tp.x][tp.y]-'a'+1;
}
else
tp.blocksNumb-=tp.map[tp.x][tp.y]-'a'+1;
}
else
tp.blocksNumb--;
tp.map[tp.x][tp.y]='.';
return 1;
}
}
}
void bfs()
{
queue<node>q;
node p,tp,pp;
int blocksNumb=0;
for(int i=0;i<R;i++)
for(int j=0;j<C;j++)
{
pp.map[i][j]=map[i][j];
if(map[i][j]!='.')
blocksNumb+=map[i][j]-'a'+1;
}
pp.blocksNumb=blocksNumb;
pp.n=0;
for(int i=0;i<R;i++)
for(int j=0;j<C;j++)
if(map[i][j]=='.') //枚举每个起始位置
{
pp.sx=i; pp.sy=j;
pp.x= i; pp.y= j;
q.push(pp);
while(!q.empty())
{
p=q.front(); q.pop();
for(int e=0;e<4;e++)
{
tp=p;
if(judge(tp,e))
{
if(tp.blocksNumb==0)
{
printf("%d\n%d\n%s\n",tp.sx,tp.sy,tp.path); return ;
}
q.push(tp);
}
}
}
}
}
int main()
{
while(scanf("%d%d",&C,&R)>0)
{
for(int i=0;i<R;i++)
scanf("%s",map[i]);
bfs();
}
}
原文:http://blog.csdn.net/u010372095/article/details/41595307