#include<iostream> //本题应重复至熟练掌握
#include<queue>
#include<cmath>
#include<string>
#include<vector>
#include<cstring>
#include<cstdio>
using namespace std;
struct Node
{
int r, c;
int dir;
Node(int r=0, int c=0, int dir=0) :r(r), c(c), dir(dir) {}
};
const int maxn = 10;
int has_edge[maxn][maxn][4][3]; //三个重要数组
int d[maxn][maxn][4];
Node p[maxn][maxn][4]; //即使无关也可增添以方便调试
int r0, c0, dir, r1, c1, r2, c2;
const char* dirs = "NESW"; //顺时针方便处理,顺序不可变//给字符编号
const char* turns = "FRL";
int dir_ID(char c)
{
return strchr(dirs, c) - dirs;
}
int turn_ID(char c)
{
return strchr(turns, c) - turns;
}
const int dr[] = { -1,0,1,0 }; //坐标移动//顺序不可变
const int dc[] = { 0,1,0,-1 };
Node walk(const Node& u, int turn)
{
int dir = u.dir;
if (turn == 1) dir = (dir + 3) % 4; // 逆时针
if (turn == 2) dir = (dir + 1) % 4; // 顺时针
return Node(u.r + dr[dir], u.c + dc[dir], dir);
}
bool inside(int r, int c)
{
return r >= 1 && r <= 9 && c >= 1 && c <= 9;
}
bool read_case() {
char s[99], s2[99];
if (scanf("%s%d%d%s%d%d", s, &r0, &c0, s2, &r2, &c2) != 6) return false;
printf("%s\n", s);
dir = dir_ID(s2[0]);
r1 = r0 + dr[dir];
c1 = c0 + dc[dir];
memset(has_edge, 0, sizeof(has_edge));
for (;;) {
int r, c;
scanf("%d", &r);
if (r == 0) break;
scanf("%d", &c);
while (scanf("%s", s) == 1 && s[0] != '*') {
for (int i = 1; i < strlen(s); i++)
has_edge[r][c][dir_ID(s[0])][turn_ID(s[i])] = 1;
}
}
return true;
}
void print_ans(Node u) {
// 从目标结点逆序追溯到初始结点
vector<Node> nodes;
for (;;) {
nodes.push_back(u);
if (d[u.r][u.c][u.dir] == 0) break;
u = p[u.r][u.c][u.dir];
}
nodes.push_back(Node(r0, c0, dir));
// 打印解,每行10个
int cnt = 0;
for (int i = nodes.size() - 1; i >= 0; i--) {
if (cnt % 10 == 0) printf(" ");
printf(" (%d,%d)", nodes[i].r, nodes[i].c);
if (++cnt % 10 == 0) printf("\n");
}
if (nodes.size() % 10 != 0) printf("\n");
}
void BFS() {
queue<Node> q;
memset(d, -1, sizeof(d)); //初始化为-1
Node u(r1, c1, dir);
q.push(u);
d[u.r][u.c][u.dir] = 0;
while (!q.empty()) {
Node u = q.front(); q.pop();
if (u.r == r2 && u.c == c2) { print_ans(u); return; } //终点
for (int i = 0; i < 3; i++) {
Node v = walk(u, i);
if (has_edge[u.r][u.c][u.dir][i] && inside(v.r, v.c) && d[v.r][v.c][v.dir] < 0) { //判断可行、范围内、未行
d[v.r][v.c][v.dir] = d[u.r][u.c][u.dir] + 1;//更新d、p,加v
p[v.r][v.c][v.dir] = u;
q.push(v);
}
}
}
printf(" No Solution Possible\n");
}
int main() {
while (read_case()) {
BFS();
}
return 0;
}
Abbott's Revenge UVA - 816(BFS典型例题)
最新推荐文章于 2021-12-08 11:30:39 发布