题意
相当于把二维的找块问题升级为三维版,并且每个块的1的和如果大于给定的T需要加起来,最后输出总的值
题目注意点
- 在每次BFS之后就返回这次的vol值
- vol值小于T时返回0
题解
解题思路:
①定义结点、矩阵、inq、增量数组
②定义判别函数,判别是否是符合的坐标
③定义BFS函数,每次找出一个块并返回里面1的个数,如果小于T则返回0
④主函数内读入matrix,定义ans存放最终结果
⑤遍历matrix中所有点,累加每次BFS的结果,最后输出
#include <stdio.h>
#include <queue>
using namespace std;
const int maxx = 1500;
const int maxy = 130;
const int maxz = 65;
struct node {
int x, y, z;
}Node;
//n行m列,l层,小于t的不计入
int m, n, l, t;
int matrix[maxx][maxy][maxz];//x,y,z
bool inq[maxx][maxy][maxz];
//增量数组
int Z[6] = {1, -1, 0, 0, 0, 0};
int Y[6] = {0, 0, 1, -1, 0, 0};
int X[6] = {0, 0, 0, 0, 1, -1};
bool test(int x, int y, int z) {
if (x<0 || x>=n || y<0 || y>=m || z<0 || z>=l) return false;
if (matrix[x][y][z] == 0 || inq[x][y][z] == true) return false;
return true;
}
int BFS(int x, int y, int z) {
int vol = 0;
queue<node> q;
Node.x = x;
Node.y = y;
Node.z = z;
q.push(Node);
vol++;
inq[x][y][z] = true;
while (!q.empty()) {
node top = q.front();
q.pop();
for (int i = 0; i < 6; i++) {
int newX = top.x + X[i];
int newY = top.y + Y[i];
int newZ = top.z + Z[i];
if (test(newX, newY, newZ)) {
Node.x = newX;
Node.y = newY;
Node.z = newZ;
q.push(Node);
inq[newX][newY][newZ] = true;
vol++;
}
}
}
if (vol >= t) return vol;
else return 0;
}
int main() {
scanf("%d%d%d%d", &m, &n, &l, &t);
for (int z = 0; z < l; z++) {
for (int y = 0; y < m; y++) {
for (int x = 0; x < n; x++) {
scanf("%d", &matrix[x][y][z]);
}
}
}
int ans = 0;
for (int z = 0; z < l; z++) {
for (int y = 0; y < m; y++) {
for (int x = 0; x < n; x++) {
if (matrix[x][y][z] == 1 && inq[x][y][z] == false) {
ans += BFS(x, y, z);
}
}
}
}
printf("%d\n", ans);
return 0;
}