优先队列,广度搜索。
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
struct node
{
int x;
int y;
int step;
int t;
friend bool operator<(node a,node b)
{
if(a.t < b.t) return true;
else if(a.t==b.t && a.step > b.step ) return true;
}
};
priority_queue<node> q;
int n,m,ans,sx,sy;
int map[110][110];
int dir[4][2]={-1,0,1,0,0,-1,0,1};
void bfs(int x,int y,int ts);
int main()
{
int i,j;
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
scanf("%d",&map[i][j]);
if(map[i][j]==2)
{
sx=i;
sy=j;
}
}
}
ans=0;
bfs(sx,sy,6);
if(!ans) printf("-1n");
}
return 0;
}
void bfs(int x,int y,int ts)
{
int i,j;
node cur,next;
cur.x = sx;
cur.y = sy;
cur.step = 0;
cur.t = ts;
while(!q.empty ()) q.pop();
q.push (cur);
while(!q.empty ())
{
cur=q.top ();
q.pop();
for(i=0;i<4;i++)
{
next.x = cur.x + dir[i][0];
next.y = cur.y + dir[i][1];
next.t = cur.t - 1;
next.step = cur.step + 1;
if(next.t < 1) continue;
if(next.x>=n || next.x<0 || next.y>=m || next.y<0) continue;
if(map[next.x][next.y]==0) continue;
if(map[next.x][next.y]==3)
{
ans=1;
printf("%dn",next.step );
return;
}
if(map[next.x][next.y]==4)
{
map[next.x][next.y]=0;
next.t = 6;
}
q.push (next);
}
}
return ;
}
注意运算符重载。