标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5891 Accepted Submission(s): 1671

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<vector>
#include<stack>
using namespace std;
int tt,n,m,map[10][10];
bool vis[10][10][10][10];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
struct node
{
int x,y,bx,by,step;
friend bool operator<(node a,node b)
{
return a.step>b.step;
}
}star;
bool check(int x,int y)
{
if(x<0||y<0||x>=n||y>=m||map[x][y]==1)
return false;
return true;
}
void input()
{
star.step=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
scanf("%d",&map[i][j]);
if(map[i][j]==2)
{
star.bx=i,star.by=j;
map[i][j]=0;
}
else if(map[i][j]==4)
{
star.x=i,star.y=j;
map[i][j]=0;
}
}
}
}
int bfs()
{
int xx,yy,x,y;
node now,next;
memset(vis,0,sizeof(vis));
vis[star.x][star.y][star.bx][star.by]=1;
priority_queue<node> q;
q.push(star);
while(!q.empty())
{
now=q.top(),q.pop();
if(map[now.bx][now.by]==3)
{
return now.step;
}
for(int i=0;i<4;i++)
{
xx=now.x+dx[i],yy=now.y+dy[i];
if(!check(xx,yy)) continue;
next.bx=now.bx;
next.by=now.by;
next.step=now.step;
next.x=xx;
next.y=yy;
if(xx==now.bx&&yy==now.by)
{
x=xx+dx[i],y=yy+dy[i];
if(!check(x,y)) continue;
next.bx=x,next.by=y;
next.step++;
}
if(vis[xx][yy][next.bx][next.by])
continue;
vis[xx][yy][next.bx][next.by]=1;
q.push(next);
}
}
return -1;
}
int main()
{
scanf("%d",&tt);
while(tt--)
{
scanf("%d%d",&n,&m);
input();
printf("%d\n",bfs());
}
return 0;
}
标签:
原文地址:http://www.cnblogs.com/a972290869/p/4355251.html