HDU 1245 推箱子


链接:http://acm.hdu.edu.cn/showproblem.php?pid=1254


#include<cstdio>
#include<stdlib.h>
#include<string.h>
#include<string>
#include<map>
#include<cmath>
#include<iostream>
#include <queue>
#include <stack>
#include<algorithm>
#include<set>
using namespace std;
#define INF 1e8
#define eps 1e-8
#define LL long long
#define maxn 2
#define mol 1000000007
int xx[8]={-1,0, 1,0,-1,0,1,0};
int yy[8]={0, -1,0,1, 0,-1,0,1};
int n,m,g[10][10];
int mat[10][10][5],flag,vis[10][10];
int bx,by,px,py;
struct point
{
    int x,y;
};
struct State
{
   point box,people;
   int step;
};
bool pd(point p)
{
     if(p.x<0||p.x>=n||p.y<0||p.y>=m||g[p.x][p.y]==1)
		 return false;
	 return true;;
}
bool bfs(point a,point b,int x,int y)
{
    memset(vis,0,sizeof(vis));
	vis[a.x][a.y]=1;
	vis[x][y]=1;
	queue<point>Q;
	Q.push(a);
	point p,q;
	while(!Q.empty())
	{
	   p=Q.front();
	   Q.pop();
	   if(p.x==b.x&&p.y==b.y) return true;
	   for(int i=0;i<4;i++)
	   {
	      q.x=p.x+xx[i];
		  q.y=p.y+yy[i];
		  if(pd(q)&&!vis[q.x][q.y])
		  {
		      Q.push(q);
			  vis[q.x][q.y]=1;
		  }
	   }
	}
	return false;
}
int main()
{
	int t,ans;
	scanf("%d",&t);
	while(t--)
	{
	   scanf("%d%d",&n,&m);
	   ans=-1;
	   memset(mat,0,sizeof(mat));
	   int i,j;
	   point st,p;
	   for(i=0;i<n;i++)
	   {
		   for(j=0;j<m;j++)
		   {
			   scanf("%d",&g[i][j]);
			   if(g[i][j]==4)
			   {
			      p.x=i;p.y=j;
			   }
			   if(g[i][j]==2)
			   {
			       st.x=i;st.y=j;
			   }
		   }
	   }
	   State f,cur,temp;
	   f.box=st;f.people =p;
	   f.step =0;
	   queue<State>q;
	   q.push(f);
	   point a,b;
	   int x,y;
	   while(!q.empty())
	   {
	      cur=q.front();
		  q.pop();
		  if(g[cur.box .x][cur.box .y]==3)
		  {
		      ans=cur.step ;
			  break;
		  }
		  for(i=0;i<4;i++)
		  {
		      temp.box .x=cur.box .x+xx[i];
			  temp.box .y=cur.box .y+yy[i];
			  temp.step =cur.step +1;
			  a=cur.people ;
			  b.x=cur.box .x-xx[i];
			  b.y=cur.box .y-yy[i];
			  x=cur.box .x;y=cur.box .y;
			  temp.people =b;
			  if(pd(temp.box)&&pd(temp.people)&&!mat[temp.box .x][temp.box .y][i]&&bfs(a,b,x,y))
			  {
			     q.push(temp);
				 mat[temp.box .x][temp.box .y][i]=1;
			  }
		  }
	   }
	   printf("%d\n",ans);
	}
return 0;
}




你可能感兴趣的:(HDU 1245 推箱子)