题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1254

1 5 5 0 3 0 0 0 1 0 1 4 0 0 0 1 0 0 1 0 2 0 0 0 0 0 0 0
4
#include <iostream>
#include <stdio.h>
#include <string>
#include <string.h>
#include <queue>
using namespace std;
int map[10][10];
int n,m,px,py,sx,sy,ex,ey;//设置全局变量,分别是人的初始位置,箱子的初始位置,箱子的终点位置
bool vis[10][10][10][10];//标志状态
int xx[]={0,0,-1,1};//设置方向数组优化广搜
int yy[]={-1,1,0,0};
struct node
{
int px,py;//人的位置
int sx,sy;
int step;
bool operator <(const node &p) const
{
return p.step<step;
}
};
void bfs(int x,int y)
{
memset(vis,false,sizeof(vis));
priority_queue<node>que;
node q,p;
q.px=x;q.py=y;q.sx=sx;q.sy=sy;q.step=0;
vis[q.px][q.py][q.sx][q.sy]=true;
que.push(q);
while(!que.empty())
{
q=que.top();
que.pop();
if(q.sx==ex&&q.sy==ey)
{
printf("%d\n",q.step);
return;
}
for(int i=0;i<4;i++)
{
p.px=q.px+xx[i];
p.py=q.py+yy[i];
p.sx=q.sx;
p.sy=q.sy;
p.step=q.step;
//判可行性
if(p.px<1||p.px>n||p.py<1||p.py>m) continue;
if(map[p.px][p.py]==1||vis[p.px][p.py][p.sx][p.sy]) continue;
if(p.px==p.sx&&p.py==p.sy)//找到箱子,那么就沿着前进这个方向推
{
p.sx=p.sx+xx[i];
p.sy=p.sy+yy[i];
p.step+=1;
//判可行性
if(p.sx<1||p.sx>n||p.sy<1||p.sy>m)continue;
if(map[p.sx][p.sy]==1||vis[p.px][p.py][p.sx][p.sy])continue;
}
que.push(p);
vis[p.px][p.py][p.sx][p.sy]=true;
}
}
printf("-1\n");
}
int main()
{
int T;
cin>>T;
while(T--)
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
{
scanf("%d",&map[i][j]);
if(map[i][j]==2)
{
sx=i;
sy=j;
//map[i][j]=0;
}
else if(map[i][j]==3)
{
ex=i;
ey=j;
// map[i][j]=0;
}
else if(map[i][j]==4)
{
px=i;
py=j;
// map[i][j]=0;
}
}
bfs(px,py);
}
return 0;
}
原文地址:http://blog.csdn.net/liusuangeng/article/details/39098781