题面
在刘汝佳紫书p165
题意
给一个迷宫,告诉起点和终点坐标,但是和平时做的迷宫不一样,不是每个点都能走上下左右4个方向,规定了进入点的方向和从该点走出的方向(比如从北方进入a点能从a点向左或者向右转,但是从东方进入a点就只能直走),求从起点到终点的最短走法
思路
看到题目必然是bfs求最短路,但是这一堆条件把我搞懵了,用了半天才吃透这个题,首先,我们肯定要记录每个点的状态,行,列,朝向,转向,是否走过,距出发点距离,该点的父亲(以便输出结果),将朝北东南西(顺时针)走的坐标变化用二维数组表示,用一个函数记录转向(前,左,右)对点朝向的影响,也用一个函数判断否出界,然后就开始bfs,node的数据成员为r,c,dir(行,列,朝向),判断三种走法是否成立(是否走过,是否越界,是否有通道),如果成立就入队,记录该点的父亲,走到终点就推出循环输出答案(利用父亲节点推回去就行)
代码
#include <bits/stdc++.h>
using namespace std;
const char *dirs = "NESW";
const char *turns = "FLR";
int next1[4][2] = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
bool book[12][12];
int r0, c0, r1, c1, dirp, rf, cf;
bool can_turn[12][12][4][3];
int d[12][12][4];
string name;
struct node
{
int r;
int c;
int dir;
node(int r = 0, int c = 0, int dir = 0) : r(r), c(c), dir(dir) {}
};
node p[12][12][4];
vector<node> anss;
node walk(node u, int turn)
{
int dir = u.dir;
if (turn == 1)
{
dir = (u.dir + 3) % 4;
}
if (turn == 2)
{
dir = (u.dir + 1) % 4;
}
return node(u.r + next1[dir][0], u.c + next1[dir][1], dir);
}
bool in(int r, int c)
{
return (r >= 1 && r <= 9 && c >= 1 && c <= 9);
}
int get_dir(char ch)
{
return strchr(dirs, ch) - dirs;
}
int get_turn(char ch)
{
return strchr(turns, ch) - turns;
}
bool read()
{
memset(can_turn, 0, sizeof(can_turn));
cin >> name;
if (name == "END")
return false;
char s[10];
cin >> r0 >> c0 >> s >> rf >> cf;
r1 = r0 + next1[get_dir(s[0])][0];
c1 = c0 + next1[get_dir(s[0])][1];
dirp = get_dir(s[0]);
int r, c;
while (cin >> r)
{
if (r == 0)
break;
cin >> c;
char ww[100];
while (cin >> ww)
{
if (ww[0] == '*')
break;
for (int i = 1; i < strlen(ww); i++)
{
can_turn[r][c][get_dir(ww[0])][get_turn(ww[i])] = 1;
// cout<<r<<' '<<c<<' '<<get_dir(ww[0])<<' '<<get_turn(ww[i])<<endl;
}
}
}
return true;
}
void print_ans(node u)
{
anss.clear();
while (1)
{
anss.push_back(u);
if(d[u.r][u.c][u.dir]==-1) break;
u=p[u.r][u.c][u.dir];
}
anss.push_back(node(r0,c0,dirp));
cout<<name<<endl;
cout<<' ';
int cnt=0;
for(int i=int(anss.size())-1;i>=0;i--)
{
if(cnt%10==0&&cnt!=0) cout<<endl<<' ';
cnt++;
cout<<' '<<'('<<anss[i].r<<','<<anss[i].c<<')';
}
cout<<endl;
}
void bfs()
{
memset(d, -1, sizeof(d));
queue<node> q;
node a;
a.r = r1;
a.c = c1;
a.dir = dirp;
q.push(a);
while (!q.empty())
{
// cout<<1<<endl;
node st = q.front();
// cout<<st.r<<' '<<st.c<<' '<<st.dir<<' '<<d[st.r][st.c][st.dir]<<' '<<can_turn[st.r][st.c][st.dir][0]<<' '<<can_turn[st.r][st.c][st.dir][1]<<' '<<can_turn[st.r][st.c][st.dir][0]<<endl;
if (st.r == rf && st.c == cf)
{
print_ans(st);
return ;
}
q.pop();
for (int i = 0; i < 3; i++)
{
node u = walk(st, i);
if (can_turn[st.r][st.c][st.dir][i] && in(u.r, u.c) && d[u.r][u.c][u.dir] < 0)
{
d[u.r][u.c][u.dir] = d[st.r][st.c][st.dir] + 1;
p[u.r][u.c][u.dir] = st;
q.push(u);
}
}
}
cout<<name<<endl<<" No Solution Possible"<<endl;
}
int main()
{
while(read())
{
bfs();
}
return 0;
}