题目链接:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=35521
/* 1:将方向用数组来表示,可方便编写代码。 2:注意题意,初始状态是刚刚离开入口 3:注意输出的格式,最后如果不满10个坐标就结束记得换行 */
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>
#include <bits/stdc++.h>
using namespace std;
const char * dir_s = "NESW";
const char * turn_s = "FLR";
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
int dirToInt(char c) {
return strchr(dir_s, c) - dir_s;
}
int turnToInt(char c) {
return strchr(turn_s, c) - turn_s;
}
struct Node {
int r, c, dir;
Node(int r = 0, int c = 0, int dir = 0) : r(r), c(c), dir(dir) {}
};
int r0, c0, dir, r1, c1, r2, c2; //分别是入口,方向,初始位置,终点位置
int has_edge[10][10][4][3]; //has_edge[r][c][dir][turn] = 1,表示在r,c位置,面向dir的点向turn转是可行的
int d[10][10][4]; //d[r][c][dir] = m 表示在点r,c,面向dir方向的点距离初始状态的最近距离是m
Node parent[10][10][4]; //表示一个点的父节点
bool read_input() {
char s[100], s1[100];
if(scanf("%s%d%d%s%d%d", s, &r0, &c0, s1, &r2, &c2) != 6 ) return false;
printf("%s\n", s); //输出此次测试情况的名称
dir = dirToInt(s1[0]);//求方向,将字母装化成数字
r1 = r0 + dr[dir];
c1 = c0 + dc[dir]; //求出初始状态
memset(has_edge, 0, sizeof(has_edge));
while(true) {
int row, col;
scanf("%d", &row);
if(row == 0) break;
scanf("%d", &col);
while(scanf("%s", s) == 1 && s[0] != '*') {
int len = strlen(s);
for(int i = 1; i < len; i++) {
has_edge[row][col][dirToInt(s[0])][turnToInt(s[i])] = 1; //读入has_edge数组
}
}
}
return true;
}
Node walk(const Node & u, int i) {
int dir = u.dir;
if(i == 1) dir = (dir + 3) % 4;
if(i == 2) dir = (dir + 1) % 4;
return Node(u.r + dr[dir], u.c + dc[dir], dir);
}
void print_ans(Node u) {
vector<Node> vec;
while(true) {
vec.push_back(u);
if(d[u.r][u.c][u.dir] == 0) break;
u = parent[u.r][u.c][u.dir];
}
vec.push_back(Node(r0, c0, dir));
int cnt = 0;
int len = vec.size();
for(int i = len - 1; i >= 0; i--) {
if(cnt % 10 == 0) printf(" ");
printf(" (%d,%d)", vec[i].r, vec[i].c);
if(++cnt % 10 == 0) printf("\n");
}
if(len % 10 != 0) printf("\n");
}
bool inside(int r, int c) {
return r >= 1 && r <= 9 && c >= 1 && c <= 9;
}
void solve() {
queue<Node> q;
Node u(r1, c1, dir);
memset(d, -1, sizeof(d));
d[u.r][u.c][u.dir] = 0;
q.push(u);
while(!q.empty()) { //bfs算法
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); //i = 0:直走 i = 1:左转 ;i = 2:右转
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;
parent[v.r][v.c][v.dir] = u;
q.push(v);
}
}
}
printf(" No Solution Possible\n");
}
int main()
{
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
while(read_input()) {
solve();
}
return 0;
}