bfs思路:
考虑 BFS搜索,考虑每个状态,所在位置 m∗n,携带钥匙状态 210,总计 20∗20∗1e3=4e5。
代码:
#include <bits/stdc++.h>
#include <stdio.h>
#include <queue>
#include <string>
using namespace std;
const int mov[4][2] = { {1,0},{-1,0},{0,1},{0,-1} };
bool vis[25][25][(1 << 10) + 5];
struct node {
pair<int, int> pos;
int state, step;
node() {
this->step = this->state = 0;
};
node(int x, int y) {
this->step = this->state = 0;
this->pos.first = x;
this->pos.second = y;
};
node(int x, int y, int state, int step) {
this->pos.first = x;
this->pos.second = y;
this->state = state;
this->step = step;
};
};
struct Map {
int n, m, t;
string mp[25];
pair<int, int> s, e;
Map() {
this->n = this->m = this->t = 0;
};
};
void out(const Map& mp, const node& p) {
printf("------------------------\nstate:");
for (int i = 0; i < 10; i++) {
if ((p.state & (1 << i)) != 0) {
printf("%c ", i + 'A');
}
}
printf(" step:%d\n",p.step);
for (int i = 0; i < mp.n; i++) {
for (int j = 0; j < mp.m; j++) {
if (i == p.pos.first && j == p.pos.second) {
cout << "%";
}
else {
cout << mp.mp[i][j];
}
}
cout << endl;
}
}
int bfs(const Map& mp) {
for (int i = 0; i < mp.n; i++) {
for (int j = 0; j < mp.m; j++) {
memset(vis[i][j], 0, sizeof(vis[i][j]));
}
}
queue<node>q;
q.push(node(mp.s.first, mp.s.second, 0, 0));
vis[q.front().pos.first][q.front().pos.second][q.front().state] = true;
while (!q.empty()) {
// out(mp, q.front());
for (int i = 0; i < 4; i++) {
int new_x = q.front().pos.first + mov[i][0],
new_y = q.front().pos.second + mov[i][1],
new_state = q.front().state,
new_step = q.front().step + 1;
if (new_x < 0 || new_x >= mp.n || new_y < 0 || new_y >= mp.m) { // 出界
continue;
}
if (mp.mp[new_x][new_y] == '*') { // 撞墙
continue;
}
if (mp.mp[new_x][new_y] <= 'j' && mp.mp[new_x][new_y] >= 'a') { // 拿钥匙
new_state = new_state | (1 << (mp.mp[new_x][new_y] - 'a'));
}
if (mp.mp[new_x][new_y] <= 'J' && mp.mp[new_x][new_y] >= 'A') { // 开门
if ((new_state & (1 << (mp.mp[new_x][new_y] - 'A'))) == 0) { // 没钥匙
continue;
}
}
if (new_x == mp.e.first && new_y == mp.e.second) { // 到达终点
return mp.t > new_step ? new_step : -1;
}
if (vis[new_x][new_y][new_state] == true) { // 到达过的状态
continue;
}
vis[new_x][new_y][new_state] = true;
q.push(node(new_x, new_y, new_state, new_step));
}
q.pop();
}
return -1;
}
int main()
{
Map x;
while (cin >> x.n >> x.m >> x.t) {
for (int i = 0; i < x.n; i++) {
cin >> x.mp[i];
for (int j = 0; j < x.m; j++) {
if (x.mp[i][j] == '@') {
x.s = make_pair(i, j);
}
if (x.mp[i][j] == '^') {
x.e = make_pair(i, j);
}
}
}
cout << bfs(x) << endl;
}
}