题意:一个n*m的图,给起点坐标和终点坐标,从起点走到终点。每个点是一堵墙或者向一个房间上下左右有门或者没门,每个点的门如题意给的。从一个点能走到下一个点的条件是两个点相对着地方都有门才能走,用时+1。在每个点有一个操作,可以把图上的每一个点顺时针旋转90度,用时+1。求起点到终点的最短用时。
我的写法:写法就是一般的bfs,比较麻烦的就是两个点之间是否能连通的问题。对于每个点,有4种状态,代表进行了在这个点进行了几次旋转操作。
判断两个点是否能走,即判断两点之间是否有门,先写一个check函数,在旋转0次时判断往分别往上下左右走的时候哪几种门能走通。4种状态,那么就需要写4个这种函数。很麻烦,但是也可以就写一个函数然后对每次要走的方向处理一下再进行判断就行了。我们可以在纸上模拟一下,往上走且当前字符是'^'但是转动了2次,直接进行判断就是把这个字符转动2次的字符找出来再对比,但是这个题情况太多,不方便这样进行判断。但是反过来想,我对走的方向进行处理行不行。试着模拟一下,发现这样是行的。意思就是,将门转动2次与将走的方向转动2次进行判断是一样的。但是处理方向就只写一个判断函数就行了。(看的别人的,感觉这个姿势很巧啊)
关于走的方向的处理,很重要。
还有我不懂的是,为什么优先队列639ms,改成队列就是327ms了。
CODE
#include <bits/stdc++.h>
using namespace std;
const int N = 1000+10;
struct node
{
int x,y;
int time; ///走到一个点的用时
int ci; ///走到一个点时转动了几次
node(int a,int b,int c,int d)
{
x = a,y = b,time = c,ci = d;
}
friend bool operator < (node a,node b)
{
return a.time > b.time;
}
};
int n,m;
int x1,y1; ///起点
int x2,y2; ///终点
char s[N][N]; ///图
bool vis[N][N][6]; ///每个点有4种状态
int dir[4][2] = {{-1,0},{0,-1},{1,0},{0,1}}; ///上左下右,方向很重要!!
bool chk(int x2,int y2) ///坐标是否合法
{
if(x2 < 1 || x2 > n || y2 < 1 || y2 > m) return false;
return true;
}
bool check(char c,int i) ///走的方向是否有门
{
if(!i) return c=='+'||c=='^'||c=='L'||c=='R'||c=='D'||c=='|';
else if(i==3) return c=='+'||c=='-'||c=='>'||c=='L'||c=='U'||c=='D';
else if(i==2) return c=='+'||c=='|'||c=='v'||c=='L'||c=='R'||c=='U';
else return c=='+'||c=='<'||c=='-'||c=='R'||c=='U'||c=='D';
}
int bfs(int x1,int y1)
{
memset(vis,false,sizeof vis);
queue<node> q;
q.push(node(x1,y1,0,0));
while(!q.empty())
{
node u = q.front();
q.pop();
if(u.x == x2 && u.y == y2)
{
return u.time;
}
if(vis[u.x][u.y][(u.ci+1)%4] == false)
{
q.push(node(u.x,u.y,u.time+1,(u.ci+1)%4));
vis[u.x][u.y][u.ci] = true;
}
for(int i = 0;i < 4;i++)
{
int tx = u.x+dir[i][0];
int ty = u.y+dir[i][1];
if(!chk(tx,ty)) continue;
if(!vis[tx][ty][u.ci] && check(s[u.x][u.y],(u.ci+i)%4) && check(s[tx][ty],(u.ci+i+2)%4))
{
q.push(node(tx,ty,u.time+1,u.ci));
vis[tx][ty][u.ci] = true;
}
}
}
return -1;
}
int main()
{
scanf("%d%d",&n,&m);
for(int i = 1;i <= n;i++)
scanf("%s",s[i]+1);
scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
int ans = bfs(x1,y1);
printf("%d\n",ans);
return 0;
}