在任何一个位置上 各有上下左右四个状态 开个三维book数组来标记即可
#include <bits/stdc++.h> using namespace std; #define N 0x3f3f3f3f struct node { bool friend operator < (node n1,node n2) { return n1.dis>n2.dis; } int x; int y; int sta; int dis; }; priority_queue <node> que; int book[20][20][4]; int n,m,p,sx,sy; char mp[20][20]; bool judge(int x,int y,int sta) { if(x<0||x>n-1||y<0||y>m-1||book[x][y][sta]||mp[x][y]=='*') return false; else return true; } int bfs() { node cur,tem; int next[4][2]={0,-1,0,1,-1,0,1,0}; int flag,ans; while(!que.empty()) que.pop(); memset(book,0,sizeof(book)); tem.x=sx,tem.y=sy,tem.sta=0,tem.dis=0; que.push(tem); book[sx][sy][0]=1; flag=0,ans=N; while(!que.empty()) { cur=que.top(); que.pop(); tem.x=cur.x,tem.y=cur.y,tem.sta=(cur.sta+1)%4,tem.dis=cur.dis+1;//右 if(tem.dis%p==0) tem.sta=(tem.sta-1+4)%4; if(judge(tem.x,tem.y,tem.sta)) { que.push(tem); book[tem.x][tem.y][tem.sta]=1; } tem.x=cur.x,tem.y=cur.y,tem.sta=(cur.sta-1+4)%4,tem.dis=cur.dis+1;//左 if(tem.dis%p==0) tem.sta=(tem.sta-1+4)%4; if(judge(tem.x,tem.y,tem.sta)) { que.push(tem); book[tem.x][tem.y][tem.sta]=1; } tem.x=cur.x+next[cur.sta][0],tem.y=cur.y+next[cur.sta][1],tem.sta=cur.sta,tem.dis=cur.dis+1;//走位 if(tem.dis%p==0) tem.sta=(tem.sta-1+4)%4; if(judge(tem.x,tem.y,tem.sta)) { if(mp[tem.x][tem.y]=='$') { flag=1; ans=min(ans,tem.dis); } else { que.push(tem); book[tem.x][tem.y][tem.sta]=1; } } tem.x=cur.x,tem.y=cur.y,tem.sta=cur.sta,tem.dis=cur.dis+1;//静 if(tem.dis%p==0) tem.sta=(tem.sta-1+4)%4; if(judge(tem.x,tem.y,tem.sta)) { que.push(tem); book[tem.x][tem.y][tem.sta]=1; } } if(!flag) return -1; else return ans; } int main() { int t,i,j,res; scanf("%d",&t); while(t--) { scanf("%d%d%d",&n,&m,&p); for(i=0;i<n;i++) { scanf("%s",mp[i]); } for(i=0;i<n;i++) { for(j=0;j<m;j++) { if(mp[i][j]=='@') { sx=i,sy=j; } } } res=bfs(); if(res==-1) printf("YouBadbad\n"); else printf("%d\n",res); } return 0; }