知识点:广度优先搜索
难度:4
这个题的难点主要是两个,首先就是状态怎么想,很明显,状态是两个点的坐标,也就是四维的,然后就是我们从一个状态,遍历它相邻的状态,这个坑还是有的,首先,不会出界,所以出界我们不用判断,其次,障碍物和蜘蛛是不一样的,障碍物如果你遇到了,那么你不能走,你的坐标要保持不变,蜘蛛是可以走上去的,接下来,如果有一个点在蜘蛛上面,那么就宣告这一步是不能走的,
我一开始把蜘蛛弄得和障碍物一样了,然后就错了,这里蜘蛛和障碍物是不一样的,障碍物可能一个走了一个不走,这样就产生了新的状态,但是如果一个遇到蜘蛛一个可以走,然后你遇到蜘蛛的退后了,这可能产生新的状态,但是按照题目的意思就是,遇到蜘蛛了,那么两个人走的步都作废了,不可能产生新的状态的,所以蜘蛛和障碍物不一样要分开处理,
#include <bits/stdc++.h>
using namespace std;
const int N = 35;
struct state {
int x1, y1, x2, y2;
state() {}
state(int a, int b, int c, int d): x1(a), y1(b), x2(c), y2(d) {}
};
int r, c, x, y, xx, yy;
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};
int ddy[4] = {0, -1, 0, 1};
string s[N];
void bfs() {
int dist[N][N][N][N];
memset(dist, -1, sizeof(dist));
dist[x][y][xx][yy] = 0;
queue<state> q;
q.push(state(x, y, xx, yy));
while (!q.empty()) {
state now = q.front(); q.pop();
if (now.x1 == now.x2 && now.y1 == now.y2 && s[now.x1][now.y1] == 'T') {
cout << dist[now.x1][now.y1][now.x2][now.y2];
return;
}
for (int i = 0; i < 4; i++) {
int u1 = now.x1 + dx[i];
int v1 = now.y1 + dy[i];
int u2 = now.x2 + dx[i];
int v2 = now.y2 + ddy[i];
if (s[u1][v1] == '#') { u1 = now.x1; v1 = now.y1; }
if (s[u2][v2] == '#') { u2 = now.x2; v2 = now.y2; }
if (dist[u1][v1][u2][v2] != -1 || s[u1][v1] == 'X' || s[u2][v2] == 'X') continue;
q.push(state(u1, v1, u2, v2));
dist[u1][v1][u2][v2] = dist[now.x1][now.y1][now.x2][now.y2] + 1;
}
}
cout << "no";
}
int main() {
cin >> r >> c;
for (int i = 0; i < r; i++) {
cin >> s[i];
for (int j = 0; j < c; j++) {
if (s[i][j] == 'M') { x = i; y = j; s[i][j] = '.'; }
if (s[i][j] == 'G') { xx = i; yy = j; s[i][j] = '.'; }
}
}
bfs();
return 0;
}