hdu 2102 BFS

本文介绍了一种基于迷宫逃脱的算法实现方案,利用BFS(宽度优先搜索)算法来解决卫兵在特定时间内能否到达指定位置的问题。该算法考虑了地图中不同元素对路径的影响,并通过代码详细展示了如何进行搜索及判断。

要注意的是要是上下两个都是传送机的话也不能进入队列,因为这样卫兵是会挂掉滴。。。。

AC代码如下:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;

typedef struct{
	int x, y, z;
	int step;
}Node;

int moves[][2] = { 1, 0, -1, 0, 0, 1, 0, -1 };
int mark[2][10][10];
char map[2][10][10];
int N, M, T;
Node P;

bool BFS(){
	Node s;
	s.x = s.y = s.z = 0;
	s.step = 0;
	mark[0][0][0] = 1;
	queue<Node> q;
	q.push( s );
	while( !q.empty() ){
		Node n = q.front();
		q.pop();
		if( n.step > T ){
			continue;
		}
		if( n.x == P.x && n.y == P.y && n.z == P.z ){
			return true;
		}
		for( int i = 0; i < 4; i++ ){
			Node temp;
			temp.x = n.x + moves[i][0];
			temp.y = n.y + moves[i][1];
			temp.z = n.z;
			temp.step = n.step + 1;
			if( temp.x < 0 || temp.x >= N || temp.y < 0 || temp.y >= M ){
				continue;
			}
			if( map[temp.z][temp.x][temp.y] == '#' && map[temp.z^1][temp.x][temp.y] == '#'){
				continue;
			}
			if( map[temp.z][temp.x][temp.y] == '#' ){
				temp.z ^= 1;
			}
			if( map[temp.z][temp.x][temp.y] == '*' ){
				continue;
			}
			if( mark[temp.z][temp.x][temp.y] == 0 || mark[temp.z][temp.x][temp.y] > temp.step ){
				mark[temp.z][temp.x][temp.y] = temp.step;
				q.push( temp );
			}
		}
	}
	return false;
}

int main(){
	int C;
	cin >> C;
	char aaa[20];
	while( C-- ){
		cin >> N >> M >> T;
		for( int k = 0; k < 2; k++ ){
			for( int i = 0; i < N; i++ ){
				scanf( "%s", aaa );
				for( int j = 0; j < M; j++ ){
					if( aaa[j] == 'P' ){
						P.x = i;
						P.y = j;
						P.z = k;
					}
					map[k][i][j] = aaa[j] ;
				}
			}
		}
		memset( mark, 0, sizeof( mark ) ); 
		if( BFS() ){
			cout << "YES" << endl;
		}else{
			cout << "NO" << endl;
		}
	}
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值