UVA816 Abbott's Revenge
阿新 • • 發佈:2018-11-03
本題和一般的迷宮問題本質上是一樣的,但是由於朝向問題,所以需要一個三元組儲存node(r, c, dir)。
#include<iostream> #include<cstdio> #include<cstring> #include<vector> #include<queue> using namespace std; const int maxn = 10; const char* dirs = "NESW"; const char* turns = "FLR"; const int dr[] = {-1, 0, 1, 0}; const int dc[] = {0, 1, 0, -1}; int d[maxn][maxn][4]; int r0, c0, dir, r1, c1, r2, c2; int hasEdge[maxn][maxn][4][3]; struct node{ int r, c; int dir; node(int r = 0, int c = 0, int dir = 0):r(r), c(c), dir(dir){} }; node p[maxn][maxn][4]; int dirId(char ch){ return strchr(dirs, ch) - dirs; } int turnId(char ch){ return strchr(turns, ch) - turns; } 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); } void print(node u){ vector<node> nodes; while(d[u.r][u.c][u.dir] != 0){ nodes.push_back(u); u = p[u.r][u.c][u.dir]; } nodes.push_back(u); nodes.push_back(node(r0, c0, dir)); 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"); } bool read(){ char s1[99], s2[99]; if(scanf("%s%d%d%s%d%d", s1, &r0, &c0, s2, &r2, &c2) != 6) return false; dir = dirId(s2[0]); printf("%s\n", s1); r1 = r0 + dr[dir]; c1 = c0 + dc[dir]; int r, c; memset(hasEdge, 0, sizeof(hasEdge)); while(scanf("%d", &r) == 1 && r){ scanf("%d", &c); while(scanf("%s", s1) == 1 && s1[0] != '*'){ for(int i = 1; i < strlen(s1); ++i){ hasEdge[r][c][dirId(s1[0])][turnId(s1[i])] = 1; } } } return true; } bool inside(int r, int c){ return r > 0 && r <= 9 && c > 0 && c <= 9; } void solve(){ node u(r1, c1, dir); memset(d, -1, sizeof(d)); queue<node> q; q.push(u); d[r1][c1][dir] = 0; while(!q.empty()){ u = q.front(); q.pop(); if(u.r == r2 && u.c == c2) {print(u); return;} for(int i = 0; i < 3; ++i){ node v = walk(u, i); if(hasEdge[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; p[v.r][v.c][v.dir] = u; q.push(v); } } } printf(" No Solution Possible\n"); } int main(){ while(read()){ solve(); } return 0; }