《算法笔记上机实验指南》 BFS

    科技2026-01-18  13

    A1091

    #include<iostream> #include<queue> using namespace std; int data[1290][130][61]; bool inq[1290][130][61]={false}; //你知道这道题的意思是和例子是一样的,不过就是要求每一块中的数字之和大于T,并且输出满足要求的数字之和 struct node { int x; int y; int z; }Node; int ans=0; int xx[6]={1,-1,0,0,0,0}; int yy[6]={0,0,1,-1,0,0}; int zz[6]={0,0,0,0,1,-1}; int m,n,l,T; bool judge(int x, int y, int z) { if(x<0 || x>=m || y<0 || y>=n || z<0 || z>=l) return false; if(inq[x][y][z]==true || data[x][y][z]==0) return false; return true; } int BFS(int x, int y, int z) //这个BFS其实就是遍历了一块中所有的点 { Node.x=x; Node.y=y; Node.z=z; inq[x][y][z]=true; queue<node> q; q.push(Node); int ans=0; //为了统计合适的数字之和,每次先设计ans为0 while(!q.empty()) //while这个队列中,其实都是存放的满足条件的数字,所以在while循环中直接对ans自增即可 { node top=q.front(); q.pop(); for(int i=0; i<6; i++) { int newX=top.x+xx[i]; int newY=top.y+yy[i]; int newZ=top.z+zz[i]; if(judge(newX,newY,newZ)) { inq[newX][newY][newZ]=true; Node.x=newX; Node.y=newY; Node.z=newZ; q.push(Node); } } ans++; } if(ans>=T) //因为题目要求统计所有合适的块的数字之和,所以直接返回每一块合适的数字之和 return ans; else //不合适的返回0 return 0; } int main() { cin >> m >> n >> l >> T; int all=0; for(int z=0; z<l; z++) for(int i=0; i<m; i++) for(int j=0; j<n; j++) { cin >> data[i][j][z]; } int ans=0; for(int z=0; z<l; z++) for(int i=0; i<m; i++) for(int j=0; j<n; j++) { if(inq[i][j][z]==false && data[i][j][z]==1) { all+=BFS(i,j,z); //对满足要求的直接进行累加 } } cout << all; return 0; }
    Processed: 0.028, SQL: 9