一开始手写了一个 递归实现的BFS,果然测试点4段错误(递归层数太多,堆栈溢出),于是参照算法笔记按队列实现BFS,对于BFS最好就用while控制循环完成BFS,不仅写法简单,而且无堆栈溢出担忧。
附本人AC代码:
#include<iostream>
#include<queue>
using namespace std;
struct Node {
int x, y, z;
};
int N, M, L, T, sum, ans = 0;
int matrix[1288][130][65];
bool flag[1288][130][65];
int X[6] = { 1,-1,0,0,0,0 };
int Y[6] = { 0,0,1,-1,0,0 };
int Z[6] = { 0,0,0,0,1,-1 };
void BFS(Node t) {
queue<Node>Q;
Q.push(t);
while (Q.size() != 0) {
Node tmp = Q.front();
Q.pop();
if (tmp.x < 0 || tmp.y < 0 || tmp.z < 0 || tmp.x >= N || tmp.y >= M || tmp.z >= L)continue;
if (flag[tmp.x][tmp.y][tmp.z] == true)continue;
if (matrix[tmp.x][tmp.y][tmp.z] == 0)continue;
flag[tmp.x][tmp.y][tmp.z] = true;
sum++;
for (int i = 0; i < 6; i++) {
Q.push({ tmp.x + X[i], tmp.y + Y[i], tmp.z + Z[i] });
}
}
}
int main() {
scanf("%d%d%d%d", &N, &M, &L, &T);
for (int i = 0; i < L; i++) {
for (int j = 0; j < N; j++) {
for (int m = 0; m < M; m++) {
scanf("%d", &matrix[j][m][i]);
}
}
}
for (int i = 0; i < L; i++) {
for (int j = 0; j < N; j++) {
for (int m = 0; m < M; m++) {
if (flag[j][m][i]==true||matrix[j][m][i]==0)continue;
sum = 0;
BFS({ j,m,i });
if (sum >= T)ans += sum;
}
}
}
printf("%d", ans);
return 0;
}