![]() ![]() |
题目大意
给出一个L层的切片,每一块切片是一个大小为M * N 的二维矩阵,其中为1的位置就是病变的位置,将这L层切片上下堆叠起来就形成了一个立体映像,二维状态的病变位置也就组成了立体的肿瘤。现在让你计算肿瘤的体积(也就是1的个数)。但是,体积不超过T的肿瘤不计数。有邻边的和满足如图所示的这种六块红色病变位置均可组成一个肿瘤。思路解析
一道十分考察耐心的题,应用的思想是三维的BFS,用DFS会导致栈溢出。首先要建立坐标系,我建立的坐标系如图所示:
创建一个三维的visited数组,每次按前后左右上下的顺序广度遍历,当队列为空时,说明遍历完了一个极大联通子图,判断体积是否符合要求,直到把所有的点都遍历完成。
示例代码
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct node {
public:
int x, y, z;
};
int m, n, l, t, temp, sum = 0;
vector<vector<vector<int>>> vec;
bool visited[70][130][1300];
int X[6] = { 0,0,-1,1,0,0 };//前后左右上下
int Y[6] = { -1,1,0,0,0,0 };
int Z[6] = { 0,0,0,0,-1,1 };
bool islegal(int z, int y, int x) {
if (x < 0 || x >= n || y < 0 || y >= m || z < 0 || z >= l) return false;
if (vec[z][y][x] == 0 || visited[z][y][x] == true) return false;
return true;
}
int bfs(int z, int y, int x) {
node nod;
int num = 0;
queue<node> que;
visited[z][y][x] = true;
nod.x = x, nod.y = y, nod.z = z;
que.push(nod);
while (!que.empty()) {
node top = que.front();
num++;
x = top.x, y = top.y, z = top.z;
que.pop();
for (int i = 0; i < 6; i++) {
int xp = x + X[i];
int yp = y + Y[i];
int zp = z + Z[i];
if (islegal(zp, yp, xp)) {
node n2;
n2.x = xp, n2.y = yp, n2.z = zp;
que.push(n2);
visited[zp][yp][xp] = true;
}
}
}
return num;
}
int main() {
scanf("%d %d %d %d", &m, &n, &l, &t);
vec.resize(l);
for (int z = 0; z < l; z++) {
vec[z].resize(m);
for (int y = 0; y < m; y++) {
for (int x = 0; x < n; x++) {
scanf("%d", &temp);
vec[z][y].push_back(temp);
}
}
}
for (int z = 0; z < l; z++) {
for (int y = 0; y < m; y++) {
for (int x = 0; x < n; x++) {
if (vec[z][y][x] == 1 && !visited[z][y][x]) {
int unit = bfs(z, y, x);
if (unit >= t) {
sum += unit;
}
}
}
}
}
cout << sum;
return 0;
}