HDU-1429

一个BFS加状态压缩的题目。


开一个map[21][21][1030]的数组用来判断是否走到重复的情况,20为图的大小,1024为10把钥匙经过状态压缩后的最大值。

即当走到某一点时,如果手上钥匙的状态和以前重复了,就说明不需要再往下走了。


#include <iostream>
#include <queue>
#include <stdio.h>
#include <string.h>
using namespace std;

struct node{
	int x,y,t,f;
};

int n,m,t,MAX;
int value[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
char map[30][30];
bool flag[21][21][1030];

int BFS(int sx,int sy){
	queue<node> q;
	node temp1,temp2;
	temp1.x = sx;
	temp1.y = sy;
	temp1.t = 0;
	temp1.f = 0;
	flag[temp1.x][temp1.y][0] = 1;
	q.push(temp1);
	while(q.empty() != true){
		temp1 = q.front();
		q.pop();
		if(temp1.t>=t-1) continue;
		temp2.t = temp1.t+1;
		for(int i=0;i<4;i++){
			temp2.x = temp1.x + value[i][0];
			temp2.y = temp1.y + value[i][1];
			temp2.f = temp1.f;
			if(temp2.x>=0 && temp2.x<m && temp2.y>=0 && temp2.y<n && map[temp2.y][temp2.x]!='*' && !flag[temp2.y][temp2.x][temp2.f]){
				if(map[temp2.y][temp2.x]>='A' && map[temp2.y][temp2.x]<='J' && ((temp2.f & (1<<(map[temp2.y][temp2.x]-'A'))) == 0)) continue;
				if(map[temp2.y][temp2.x]>='a' && map[temp2.y][temp2.x]<='j'){
					temp2.f = temp2.f | (1<<(map[temp2.y][temp2.x]-'a'));
					flag[temp2.y][temp2.x][temp2.f] = 1;
					q.push(temp2);
					continue;
				}
				if(map[temp2.y][temp2.x] == '^') return temp2.t;
				flag[temp2.y][temp2.x][temp2.f] = 1;
				q.push(temp2);
			}
		}
	}
	return -1;
}

int main(){
	int i,j,sx,sy,SUM,temp;
	while(cin>>n>>m>>t){
		for(i=0;i<n;i++) scanf("%s",&map[i]);
		for(i=0;i<n;i++){
			for(j=0;j<m;j++){
				if(map[i][j] == '@'){
					sx = j;
					sy = i;
				}
			}
		}
		memset(flag,0,sizeof(flag));
		printf("%d\n",BFS(sx,sy));
	}
	return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值