Sample Input:
3 4 5 2
1 1 1 1
1 1 1 1
1 1 1 1
0 0 1 1
0 0 1 1
0 0 1 1
1 0 1 1
0 1 0 0
0 0 0 0
1 0 1 1
0 0 0 0
0 0 0 0
0 0 0 1
0 0 0 1
1 0 0 0
Sample Output:
26
题解:
此题直接采用BFS,对遍历过的点需要标记,避免再次遍历
#include <iostream>
#include <queue>
using namespace std;
bool visit[1300][140][70];
int matrix[1300][140][70];
int X[6]={1,0,0,0,-1,0};
int Y[6]={0,1,0,-1,0,0};
int Z[6]={0,0,1,0,0,-1};
int m,n,l,t;
struct node{
int x,y,z;
};
bool judge(int x,int y,int z){
if(x < 0 || y < 0 || z < 0 || x >= m || y >= n || z >= l) return false;
if(matrix[x][y][z] == 0 || visit[x][y][z] == true) return false;
return true;
}
int bfs(int x,int y,int z){
queue<node> q;
node temp;
temp.x = x,temp.y = y,temp.z=z;
q.push(temp);
visit[x][y][z] = true;
int count = 0;
while(!q.empty()){
node top = q.front();
q.pop();
count++;
for(int i=0;i<6;i++){
int t_x = top.x + X[i];
int t_y = top.y + Y[i];
int t_z = top.z + Z[i];
if(judge(t_x,t_y,t_z)){
temp.x = t_x,temp.y = t_y,temp.z= t_z;//此处如果用top替换,再将top入队的话会有两个测试点通不过
visit[t_x][t_y][t_z] = true;
q.push(temp);
}
}
}
if(count >= t) return count;
else return 0;
}
int main(){
cin >> m >> n >> l >> t;
for(int z=0;z<l;z++){
for(int x=0;x<m;x++){
for(int y=0;y<n;y++){
scanf_s("%d",&matrix[x][y][z]);
}
}
}
int ans=0;
for(int z=0;z<l;z++){
for(int x=0;x<m;x++){
for(int y=0;y<n;y++){
if(matrix[x][y][z] == 1 && visit[x][y][z] == false){
ans += bfs(x,y,z);
}
}
}
}
cout << ans;
system("pause");
return 0;
}