九度:1456 <BFS><胜利大逃亡>

7 篇文章 0 订阅


http://ac.jobdu.com/problem.php?pid=1456

思路

定义:
map、mark、队列Q、节点Node
int bfs (参数)
{
	while(!Q.empty())
	{
		Node now 获取队头节点
		for(每个方向)
		{
			求出下一节点坐标t
			if t 越界:continue;下一个方向的节点
			if t 墙壁:continue;下一个方向的节点
			if t 已访问:continue;下一个方向的节点
			更新t的信息
			将节点t入队列
			if t 为终点:返回结果
		}
	}
	return 结果不存在时的结果
}

初始化起点信息:
mark标记为true
处理起点信息
入队


代码

// 九度:1456 
// BFS
// 
// 

// 迷宫类bfs

#include <stdio.h>
#include <queue>

#define SIZE 55

using namespace std;

int map[SIZE][SIZE][SIZE];
bool mark[SIZE][SIZE][SIZE];

struct Node{
	int x, y, z;
	int t;
};

queue<Node> Q;

int dir[][3]={
	1,0,0,
	-1,0,0,
	0,1,0,
	0,-1,0,
	0,0,1,
	0,0-1
};

void Init()
{
	//memset(map, 0, sizeof(map));
	//memset(mark, 0, sizeof(mark));//二者的每一个值都会输入处理,所以在此没必要初始化
	while( !Q.empty())
	{
		Q.pop();
	}
}

void Input(const int a,const int b,const int c)
{
	for(int i=0; i<a; i++)
	{
		for(int j=0; j<b; j++)
		{
			for(int k=0; k<c; k++)
			{
				scanf("%d", &map[i][j][k]);
				mark[i][j][k] = false;//输入时修改标记
			}
		}
	}
	return ;
}

int bfs(int a, int b, int c)
{
	while( !Q.empty())
	{
		Node now = Q.front();
		Q.pop();
		for(int i=0; i<6; i++)
		{
			int nx = now.x + dir[i][0];
			int ny = now.y + dir[i][1];
			int nz = now.z + dir[i][2];
			if(nx<0 || nx>=a || ny<0 || ny>=b || nz<0 || nz>=c)
			{
				continue;
			}// 越界
			if(map[nx][ny][nz] == 1)
			{
				continue;
			}// 墙壁

			///  一个隐蔽的错误   ///
			//
			//   mark[nx][ny][nz] == true
			//   错打为 mark[nx][ny][nz] = true
			//
			//   写为下面的格式,常亮放到左边,如果输入为赋值,会提示错误
			/
			
			if(true == mark[nx][ny][nz])
			{
				continue;
			}// 已访问

			Node next;
			next.x = nx;
			next.y = ny;
			next.z = nz;
			next.t = now.t+1;
			Q.push(next);//符合,入队
			mark[nx][ny][nz] = true;//标记为已访问 
			if(nx == a-1 && ny == b-1 && nz == c-1)
			{
				return next.t;//返回到终点的时间
			}
		}//for
	}//while

	return -1;//已遍历后,还没有到达终点
}


int main()
{
#ifdef ONLINE_JUDGE
#else
	freopen("E:\\in.txt", "r", stdin);
	//freopen("E:\\out.txt", "w", stdout);
#endif

	int k;
	scanf("%d", &k) ;
	while(k-->0)
	{
		Init();
		int a, b, c, t;
		scanf("%d%d%d%d", &a, &b, &c, &t);
		Input(a, b, c);

		///    bfs核心区            //
		
		mark[0][0][0] = true;//起点标记为已访问
		Node temp;
		// temp.x = 0;
		// temp.y = 0;
		// temp.z = 0;
		// temp.t = 0;
		temp.x = temp.y = temp.z = temp.t = 0;//起点入队
		
		Q.push(temp);
		int ans = bfs(a, b, c);//开始bfs
		if(ans <= t)//不能达到时bfs返回-1,所以不能到达或者在规定时间内到达,均可输出。
		{
			printf("%d\n", ans);
		}
		else//超时,输出-1
		{
			printf("-1\n");
		}
		
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值