裸的bfs,感觉每个点可以走多次,于是用个三维数据记录了,具体没细想,早睡早起,要开始复习期末了
/* author:jxy lang:C/C++ university:China,Xidian University **If you need to reprint,please indicate the source** */ #include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <queue> #define INF 1E9 using namespace std; const int dir[4][2]={1,0,-1,0,0,1,0,-1}; int map[10][10],n,m; struct node { int x,y,t,s; }; bool vis[10][10][7]; int dis[10][10]; queue<node> q; int ex,ey; node now,next; int bfs(int x,int y) { while(!q.empty())q.pop(); memset(dis,0,sizeof(dis)); memset(vis,0,sizeof(vis)); dis[x][y]=1; vis[x][y][6]=1; now.x=x;now.y=y;now.t=6;now.s=1; q.push(now); int i; while(!q.empty()&&!dis[ex][ey]) { now=q.front();q.pop(); next.s=now.s+1; if(now.t==1)continue; for(i=0;i<4;i++) { next.t=now.t-1; next.x=now.x+dir[i][0]; next.y=now.y+dir[i][1]; if(next.x<0||next.y<0||next.x>=n||next.y>=m||map[next.x][next.y]==0)continue; if(map[next.x][next.y]==4)next.t=6; if(vis[next.x][next.y][next.t])continue; if(!dis[next.x][next.y]||dis[next.x][next.y]>next.s)dis[next.x][next.y]=next.s; q.push(next); vis[next.x][next.y][next.t]=1; } } return dis[ex][ey]-1; } int main() { int T; scanf("%d",&T); while(T--) { scanf("%d%d",&n,&m); int i,j,x,y; for(i=0;i<n;i++) for(j=0;j<m;j++) { scanf("%d",&map[i][j]); if(map[i][j]==2)x=i,y=j; if(map[i][j]==3)ex=i,ey=j; } printf("%d\n",bfs(x,y)); } }