题意:从M走到T,路上有摄像头,且每一秒都顺时针转90,摄像头可以照到旁边相邻的位置,如果被照到的话,走一步的时间为3,正常走的话时间+1,你也可以选择呆在原地不动,但时间也+1;问最短时间走到T
思路:用bfs搜索,用优先队列维护最短的时间,每一个点的状态有四个,所以记录时的数组应该是5倍的,具体看注释
#include <queue>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const int maxn=510;
int dir[4][2]={{0,-1},{-1,0},{0,1},{1,0}};
char str[maxn][maxn];
int v[maxn][maxn][5],sx,sy,ex,ey,change[maxn*maxn],n;
//一个点可以有四个时间段走过,所以定义为v[maxn][maxn][5];
struct edge{
int x,y,step;
bool operator <(const edge &b)const {
return step>b.step;
}
};
int judge(int x,int y,int step){
//判断是否在灯的照射下,如果返回0说明此点不能走,返回1说明被灯照着,返回2正常走
if(x<0||x>n-1||y<0||y>n-1||str[x][y]=='#') return 0;
if(change[x*n+y]!=-1) return 1;//这个点是摄像头的位置,返回1
for(int i=0;i<4;i++){
int xx=dir[i][0]+x,yy=dir[i][1]+y;
if(xx<0||xx>n-1||yy<0||yy>n-1) continue;
int t=change[xx*n+yy];//自己找坐标画一下就能看出来了
if(t>=0&&(t+step)%4==i) return 1;
}
return 2;
}
int bfs(){
priority_queue<edge>que;
memset(v,0,sizeof(v));
edge c,ne;
c.x=sx,c.y=sy,c.step=0;
que.push(c);
while(!que.empty()){
c=que.top();que.pop();
if(c.x==ex&&c.y==ey) return c.step;
int t=c.step+1;
//不动的情况,时间+1
if(v[c.x][c.y][t%4]==0){
v[c.x][c.y][t%4]=1;
ne.x=c.x;ne.y=c.y;ne.step=t;
que.push(ne);
}
int flag=judge(c.x,c.y,c.step);
for(int i=0;i<4;i++){
int xx=c.x+dir[i][0],yy=c.y+dir[i][1],tt;
int che=judge(xx,yy,c.step);
if(che==0) continue;
if(che==1||flag==1) tt=c.step+3;//被照到的情况前行,时间+3
else if(che==2) tt=c.step+1;//没被照到+1
if(v[xx][yy][tt%4]==0){
v[xx][yy][tt%4]=1;
ne.x=xx;ne.y=yy;ne.step=tt;
que.push(ne);
}
}
}
return -1;
}
int main(){
int T,t=1;
scanf("%d",&T);
while(T--){
scanf("%d",&n);
memset(change,-1,sizeof(change));
for(int i=0;i<n;i++) scanf("%s",str[i]);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(str[i][j]=='M'){
sx=i;sy=j;
}else if(str[i][j]=='T'){//对四个方向分别定下一个值
ex=i;ey=j;
}else if(str[i][j]=='E'){
change[i*n+j]=0;
}else if(str[i][j]=='S'){
change[i*n+j]=1;
}else if(str[i][j]=='W'){
change[i*n+j]=2;
}else if(str[i][j]=='N'){
change[i*n+j]=3;
}
}
}
int ans=bfs();
printf("Case #%d: %d\n",t++,ans);
}
return 0;
}