做的前一道是DFS,直接下意识的用DFS做,但是BFS明显可以有先后顺序判断到的前后,不需要另外判断,因此用BFS简单很多
参考代码及逻辑
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
int Line[10][10];
int Ltime[10][10];
int Neet[10][10];
int N, M;
int X[] = {0, 0, 1, -1};
int Y[] = {1, -1, 0, 0};
struct Node {
int x;
int y;
int t;
int anst;
};
void BFS(Node node, int x2, int y2) {
Node ch;
queue<Node> qu;
qu.push(node);
while (!qu.empty()) {
node = qu.front();
qu.pop();
for (int i = 0; i < 4; ++i) {
ch.x = node.x + X[i];
ch.y = node.y + Y[i];
ch.t = node.t - 1;
ch.anst = node.anst + 1;
if (ch.t <= 0)
break;
if (Line[ch.x][ch.y] == 0)
continue;
if (ch.x == x2 && ch.y == y2) {
Ltime[ch.x][ch.y] = ch.t;
Neet[ch.x][ch.y] = ch.anst;
return ;
}
if (Line[ch.x][ch.y] == 4) {
ch.t = 6;
if (Ltime[ch.x][ch.y] == -1) {
Ltime[ch.x][ch.y] = 6;
} else {
continue;
}
}
if (Ltime[ch.x][ch.y] < ch.t) {
Ltime[ch.x][ch.y] = ch.t;
}
qu.push(ch);
}
}
}
int main() {
int n;
cin >> n;
int x1, x2, y1, y2;
while (n--) {
cin >> N >> M;
for (int i = 1; i <= N; ++i) {
for (int j = 1; j <= M; ++j) {
cin >> Line[i][j];
Ltime[i][j] = -1;
if (Line[i][j] == 2) {
x1 = i;
y1 = j;
}
if (Line[i][j] == 3) {
x2 = i;
y2 = j;
}
}
}
memset(Ltime, -1, sizeof(Ltime));
for (int i = 0; i <= M + 1; ++i ) {
Line[0][i] = 0;
Line[N + 1][i] = 0;
Ltime[0][i] = -1;
Ltime[N + 1][i] = -1;
}
for (int i = 0; i <= N + 1; ++i) {
Line[i][0] = 0;
Line[i][M + 1] = 0;
Ltime[i][0] = -1;
Ltime[i][M + 1] = -1;
}
Node node;
node.t = 6;
node.x = x1;
node.y = y1;
node.anst = 0;
Neet[x2][y2] = -1;
BFS(node, x2, y2);
cout << Neet[x2][y2] << endl;
}
return 0;
}