http://acm.uestc.edu.cn/#/problem/show/149
其实没有想象中那么难,就是bfs。
要注意在传送门中往返,走一个门封一个门。
#include<iostream>
#include <cstring>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
using namespace std;
const int INT = 2147483647;
int dir[4][2] = { { 1,0 },{ -1,0 },{ 0,1 },{ 0,-1 } };
int lx, ly, qx, qy, n, m, ans;
char mapn[55][55];
int vis[55][55];
struct Note {
int x;
int y;
int spet;
}note;
map<char, Note> mm;
void BFS(Note nn) {
queue<Note> q;
q.push(nn);
while (!q.empty()) {
for (int i = 0; i < 4; i++) {
note.x = q.front().x + dir[i][0];
note.y = q.front().y + dir[i][1];
note.spet = q.front().spet + 1;
if (note.x >= 0 && note.x < n && note.y >= 0 && note.y<m && mapn[note.x][note.y] != '#'&& vis[note.x][note.y]>note.spet) {
if (note.x == qx && note.y == qy) {
ans = note.spet;
return;
}
else if ('a' <= mapn[note.x][note.y] && mapn[note.x][note.y] <= 'z') {
int x = note.x, y = note.y;
vis[x][y] = note.spet;
note.x = mm[mapn[x][y] - 'a' + 'A'].x;
note.y = mm[mapn[x][y] - 'a' + 'A'].y;
q.push(note);//允许往返一次
continue;
}
else if ('A' <= mapn[note.x][note.y] && mapn[note.x][note.y] <= 'Z') {
int x = note.x, y = note.y;
vis[x][y] = note.spet;
note.x = mm[mapn[x][y] - 'A' + 'a'].x;
note.y = mm[mapn[x][y] - 'A' + 'a'].y;
q.push(note);
continue;
}
q.push(note);
vis[note.x][note.y] = note.spet;
}
}
q.pop();
}
}
int main() {
int T;
scanf("%d", &T);
while (T--) {
ans = -1;
mm.clear();
scanf("%d%d", &n, &m);
getchar();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
vis[i][j] = INT;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
scanf("%c", &mapn[i][j]);
if (mapn[i][j] == 'L') {
lx = i;
ly = j;
}
if (mapn[i][j] == 'Q') {
qx = i;
qy = j;
}
if ('a' <= mapn[i][j] && mapn[i][j] <= 'z') {
note.x = i;
note.y = j;
map<char, Note>::iterator it;;
it = mm.find(mapn[i][j]);
if (it == mm.end()) {
mm.insert(pair <char, Note>(mapn[i][j], note));
}
else {
mapn[i][j] = mapn[i][j] - 'a' + 'A';
mm.insert(pair <char, Note>(mapn[i][j], note));
}
}
}
getchar();
}
note.x = lx;
note.y = ly;
note.spet = 0;
vis[lx][ly] = 0;
BFS(note);
printf("%d\n", ans);
}
return 0;
}