HDU1253 基础BFS


很无语的一道题。。但现在想想也就那样,题很简单,你说出题人坑,那还是你自己没有考虑完全,再坑总会有人一遍过的。

#include 
#include 
#include 
#include 
using namespace std;
const int AX = 55;
int mp[AX][AX][AX];
int A,B,C,t;
int vis[AX][AX][AX];
int dir[6][3]={{1,0,0},{0,1,0},{0,0,1},{-1,0,0},{0,-1,0},{0,0,-1}};

struct Node
{
	int x,y,z;
	int step;
}pos,q,p;

int bfs(){
	if(A-1 == 0 && B-1 ==0 && C-1 == 0) return 0;
	queueque;
	pos.x = 0 ; pos.y = 0 ; pos.z = 0;
	pos.step = 0 ;
	vis[0][0][0] = 1;
	que.push(pos);
	while( !que.empty() ){
		q = que.front();
		que.pop();
		for( int i = 0 ; i < 6; i ++ ){
			int xx = q.x + dir[i][0];
			int yy = q.y + dir[i][1];
			int zz = q.z + dir[i][2];
			if( xx >= 0 && xx <= A-1 && yy >=0 && yy <= B-1 && zz >=0 && zz <= C-1 && q.step+1 <=t && mp[xx][yy][zz] == 0 && !vis[xx][yy][zz] ){
				if( xx == A-1 && yy == B-1 && zz == C-1 ) return q.step + 1;
				p.x = xx; p.y = yy ; p.z = zz; p.step = q.step + 1;
				que.push(p);
				vis[xx][yy][zz] = 1;
			}
		}
	}
	return -1;
}

int main(){
	int T;
	scanf("%d",&T);
	while( T-- ){
		memset(vis,0,sizeof(vis));
		scanf("%d%d%d%d",&A,&B,&C,&t);
		for( int i = 0 ; i < A ; i++ ){
			for( int j = 0 ; j < B ; j++ ){
				for( int k = 0 ; k < C ; k++ ){
					scanf("%d",&mp[i][j][k]);
				}
			}
		}
			int ans = bfs();
			if( ans >= 0  ) printf("%d\n",ans);
			else printf("-1\n");
	}
	return 0;
}

你可能感兴趣的:(暑期集训刷题算法复习(新手,),图-BFS)