这道题目一开始wa的有点莫名其妙;CP了两次因为 node next 没有定义在BFS 函数里面。WA了好几次因为 queue<node>q 没有定义在BFS函数里面。到现在也没太搞明白这有什么关系,和OJ有关?
其余的话就是比较裸的BFS了;
#include<iostream> #include <stdio.h> #include <string.h> #include<functional> #include<queue> using namespace std; int n,m,mapp[10][10]; struct node { int x,y,step,time; }st,ed; int dir[][2]={1,0 ,-1,0 ,0,1 ,0,-1}; int BFS() { queue <node>q; node next; node cur; cur.x=st.x; cur.y=st.y; cur.step=0; cur.time=6; next.time=6; q.push(cur); while(!q.empty()) { cur=q.front(); q.pop(); for(int i=0;i<4;i++) { next.x=cur.x+dir[i][0]; next.y=cur.y+dir[i][1]; next.time=cur.time-1; next.step=cur.step+1; if( next.time>0 && mapp[next.x][next.y] && next.x>0 && next.x<=n && next.y>0 && next.y<=m) { // printf("(%d %d)->(%d %d) time=%d\n",cur.x,cur.y,next.x,next.y,next.time); // next.time=cur.time-1; // next.step=cur.step+1; if(next.x==ed.x && next.y==ed.y ) { return next.step; } if(mapp[next.x][next.y]==4) { next.time=6; mapp[next.x][next.y]=0; } q.push(next); } } } return -1; } int main() { int T; scanf("%d",&T); while(T--) { scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) { scanf("%d",&mapp[i][j]); if(mapp[i][j]==2) { st.x=i; st.y=j; } if(mapp[i][j]==3) { ed.x=i; ed.y=j; } } int ans=BFS(); printf("%d\n",ans); } return 0; }