团体程序设计天梯赛
L3-004 肿瘤诊断
三维的图搜索。可以使用bfs
/dfs
. 每次搜索移动当前位置,使用x
, y
, z
三个数组实现。每次访问节点需判断节点是否越界/是否有肿瘤/是否访问过。bfs可以使用队列实现;dfs可以使用递归或堆栈实现。
#include <bits/stdc++.h>
using namespace std;
int m, n, l, t;
int ballMap[1300][130][64];
bool visited[1300][130][64];
int dx[6] = {1, 0, 0, -1, 0, 0};
int dy[6] = {0, 1, 0, 0, -1, 0};
int dz[6] = {0, 0, 1, 0, 0, -1};
struct node{ int x, y, z; };
bool haveBall(int x, int y, int z){
if(x < 0 || y < 0 || z < 0 || x >= m || y >= n || z >= l) return false;
if (visited[x][y][z]) return false;
if (ballMap[x][y][z] == 0) return false;
return true;
}
int bfs(int x, int y, int z){
if(!haveBall(x, y, z)) return 0;
int size = 0;
queue<node> q;
node first;
first.x = x; first.y = y; first.z = z;
q.push(first);
visited[x][y][z] = 1;
size++;
while(!q.empty()){
node top = q.front();
q.pop();
for(int i = 0; i <= 5; i++){
int nx = top.x + dx[i];
int ny = top.y + dy[i];
int nz = top.z + dz[i];
if(haveBall(nx, ny, nz)){
node temp;
temp.x = nx; temp.y = ny; temp.z = nz;
q.push(temp);
size++;
visited[nx][ny][nz] = 1;
}
}
}
return size;
}
int main(){
cin >> m >> n >> l >> t;
for(int i = 0; i <= l - 1; i++)
for(int j = 0; j <= m - 1; j++)
for(int k = 0; k <= n - 1; k++)
cin >> ballMap[j][k][i];
int sum = 0, temp;
for(int i = 0; i <= l - 1; i++)
for(int j = 0; j <= m - 1; j++)
for(int k = 0; k <= n - 1; k++){
temp = bfs(j, k, i);
if(temp >= t) sum += temp;
}
cout << sum << endl;
return 0;
}