本题重点是访问完一次4之后要置成1或者0,防止多次重置。
因为这个我错了好多次。
代码:
#include <cstdio>
#include <queue>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
typedef struct {
int x,y;
int time;
int step;
}node;
node st;
int n,m;
int a[10][10];
int enx,eny;
int dx[] = {-1,0,1,0};
int dy[] = {0,1,0,-1};
struct cmp{
bool operator()(node i,node j)
{
return i.step > j.step;
}
};
int bfs()
{
priority_queue<node,vector<node>,cmp> q;
node t,head;
st.time = 6;
st.step = 0;
q.push(st);
while(!q.empty())
{
head = q.top();
q.pop();
// printf("%d %d %d %d\n",head.x,head.y,head.time,head.step);
if(head.time == 1)
continue;
if(head.x == enx && head.y == eny && head.time > 0)
{
return head.step;
}
for(int i = 0;i < 4;++i)
{
t.x = head.x + dx[i];
t.y = head.y + dy[i];
t.step = head.step + 1;
t.time = head.time - 1;
if(t.x >= 1 && t.x <= n && t.y >= 1 && t.y <= m && a[t.x][t.y])
{
if(a[t.x][t.y] == 4 && t.time > 0)
{
a[t.x][t.y] = 1;
t.time = 6;
}
else if(a[t.x][t.y] == 3 && t.time > 0)
{
return t.step;
}
q.push(t);
}
}
}
return -1;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
// memset(v,0,sizeof(v));
scanf("%d%d",&n,&m);
for(int i = 1;i <= n;++i)
{
for(int j = 1;j <= m;++j)
{
scanf("%d",&a[i][j]);
if(a[i][j] == 2)
{
st.x = i;
st.y = j;
}
else if(a[i][j] == 3)
{
enx = i;
eny = j;
}
}
}
printf("%d\n",bfs());
// printf("%d %d %d %d\n",stx,sty,enx,eny);
}
}