例题6-14 Abbott的复仇(Abbott's Revenge, ACM/ICPC World Finals 2000, UVa816)
程序员文章站
2024-03-19 15:37:04
...
原题链接:https://vjudge.net/problem/UVA-816
分类:图
备注:图的最短路(BFS)
前段时间已经做过一些BFS了,做这个就看了看紫书上的翻译,比较关键的是看了下怎么存储路径,大概懂了就很容易了。
代码如下:
#include<string>
#include<cstdio>
#include<vector>
#include<cstring>
#include<iostream>
#include<queue>
#include<map>
using namespace std;
const int dir[4][2] = { {-1,0},{0,1},{1,0},{0,-1} };//NESW
int vised[10][10][4];
int ok[10][10][4][4];
int sr, sc, er, ec;
char toward;
map<char, int>to;
struct node{
int r, c;
int t;
node() :r(0), c(0), t(0) {}
node(int row, int col, int toward) {
r = row; c = col; t = toward;
}
}p[10][10][4];
vector<node>ans;
bool readdir(int row, int col) {
char ch = getchar();
if (ch == '*')return false;
int tt = to[ch]; ch = getchar();
while (ch != ' ') {
int tt2 = tt;
if (ch == 'L')tt2 = (tt + 3) % 4;
if (ch == 'R')tt2 = (tt + 1) % 4;
ok[row][col][tt][tt2] = 1;
ch = getchar();
}
return true;
}
bool solve() {
node head, next;
head.t = to[toward];
head.r = sr + dir[to[toward]][0];
head.c = sc + dir[to[toward]][1];
queue<node>q;
q.push(head);
while (!q.empty()) {
head = q.front(); q.pop();
if (head.r == er && head.c == ec) {
node u = head;
for (;;) {
ans.push_back(u);
if (!p[u.r][u.c][u.t].r)break;
u = p[u.r][u.c][u.t];
}
ans.push_back(node(sr, sc, toward));
return true;
}
for (int i = 0; i < 4; i++) {
if (!ok[head.r][head.c][head.t][i])continue;
int rr = head.r + dir[i][0];
int cc = head.c + dir[i][1];
if (vised[rr][cc][i])continue;
next.r = rr; next.c = cc;
next.t = i;
vised[rr][cc][i] = 1;
p[rr][cc][i] = head;
q.push(next);
}
}
printf(" No Solution Possible\n");
return false;
}
int main(void) {
to['N'] = 0; to['E'] = 1;
to['S'] = 2; to['W'] = 3;
string name;
while (cin >> name && name != "END") {
ans.clear();
memset(p, 0, sizeof(p));
memset(vised, 0, sizeof(vised));
memset(ok, 0, sizeof(ok));
scanf("%d %d %c %d %d", &sr, &sc, &toward, &er, &ec);
int row, col;
while (~scanf("%d", &row) && row) {
scanf("%d", &col); getchar();
while (readdir(row, col));
}
printf("%s\n", name.c_str());
if (solve()) {
for (int i = ans.size() - 1, cnt = 0; i >= 0; i--) {
if (++cnt % 10 == 1)printf(" ");
printf(" (%d,%d)", ans[i].r, ans[i].c);
if (cnt % 10 == 0)printf("\n");
}
if (ans.size() % 10 != 0)printf("\n");
}
}
return 0;
}
上一篇: 二分查找递归实现和非递归实现