(1)问题描述:
对于三维空间的某一个坐标而言,如果它的上、下、左、右、前后都有food cubes的话,这个坐标就可以称之为一个hole。
现在给出所有food cubes的坐标,需要求出有多少个holes。
坐标x、y、z的范围都是1-100
(2)基本思路:
对于不是food cubes的坐标,进行广度优先搜索。
假设搜索完整个空间需要count次,则hole的个数是(count - 1)。
需要注意的是边界条件的判断(想象一个2乘2的立方体,左上角和右下角是food cubes,那么它的hole数应该是0,就可以知道为什么边界条件这样设置了)。
bool valid(int x, int y, int z)
{
return (x >= 0 && x <= 101 && y >= 0 && y <= 101 && z >= 0 && z <= 101);
}
(3)代码实现:
#include<iostream>
#include<queue>
using namespace std;
#define MAX 102
int cube[MAX][MAX][MAX];
int dx[6] = {0, 0, 1, -1, 0, 0};
int dy[6] = {0, 0, 0, 0, 1, -1};
int dz[6] = {1, -1, 0, 0, 0, 0};
struct Node
{
int x, y, z;
Node(int _x, int _y, int _z)
{
x = _x;
y = _y;
z = _z;
}
};
bool valid(int x, int y, int z)
{
return (x >= 0 && x <= 101 && y >= 0 && y <= 101 && z >= 0 && z <= 101);
}
void bfs(int sx, int sy, int sz)
{
int tx;
int ty;
int tz;
queue<Node> q;
q.push(Node(sx, sy, sz));
cube[sx][sy][sz] = 1;
while(!q.empty())
{
Node top = q.front();
for(int i = 0; i < 6; i++)
{
tx = top.x + dx[i];
ty = top.y + dy[i];
tz = top.z + dz[i];
if(valid(tx, ty, tz) && cube[tx][ty][tz] == 0)
{
q.push(Node(tx, ty, tz));
cube[tx][ty][tz] = 1;
}
}
q.pop();
}
}
int main()
{
int t;//number of test cases
cin >> t;
while(t--)
{
int m;//the number of food cubes
int x, y, z;
cin >> m;
for(int i = 0; i < MAX; i++)
{
for(int j = 0; j < MAX; j++)
{
for(int l = 0; l < MAX; l++)
cube[i][j][l] = 0;
}
}
for(int i = 0; i < m; i++)
{
cin >> x >> y >> z;
cube[x][y][z] = 1;
}
int count = 0;
for(int i = 0; i < MAX; i++)
{
for(int j = 0; j < MAX; j++)
{
for(int l = 0; l < MAX; l++)
{
if(cube[i][j][l] == 0)
{
bfs(i, j, l);
count++;
}
}
}
}
cout << count - 1 << endl;
}
return 0;
}