hdu 1429胜利大逃亡(续) / sdut 2193 救基友记3(BFS)

这篇博客介绍了如何使用BFS解决hdu 1429胜利大逃亡和sdut 2193救基友记3的问题。作者在完成热身赛后发现这两道题目可以通过增加标记数组的一维来解决,利用mark[][][1<<10+10]记录到达每个点时拥有的钥匙状态,其中涉及10种不同的钥匙。
摘要由CSDN通过智能技术生成

http://acm.hdu.edu.cn/showproblem.php?pid=1429

做了热身赛http://blog.csdn.net/u013081425/article/details/21740001 之后发现这道题好水,之前怎么没刷到呢。。

同样标记数组增加一维,标记到某一点时他拥有钥匙的状态,因为有10种钥匙,所以mark[][][1<<10+10]来标记每到一点的状态。


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

int dir[4][2] = { {-1,0},{1,0},{0,-1},{0,1} };
struct node
{
	int x,y;
	int step;
	int sta;
}p[410];

queue <struct node> que;
char map[30][30];
int n,m,t;
int sx,sy;
int mark[30][30][1<<10+10];

void bfs()
{
	memset(mark,0,sizeof(mark));
	while(!que.empty()) que.pop();
	que.push((struct node) {sx,sy,0,0});
	mark[sx][sy][0] = 1;
	while(!que.empty())
	{
		struct node u = que.front();
		que.pop();
		if(u.step >= t)
        {
            printf("-1\n");
            return;
        }
		if(map[u.x][u.y] == '^')
        {
            printf("%d\n",u.step);
            return;
        }
		for(int d = 0; d <= 3; d++)
		{
			int x = u.x+dir[d][0];
			int y = u.y+dir[d][1];
            if(x < 1 || x > n || y < 1 || y > m)
                continue;
			int sta = u.sta;
			int add;
			if(map[x][y] == '.' || map[x][y] == '@' || map[x][y] == '^')
			{
				if(!mark[x][y][sta])
				{
					que.push((struct node){x,y,u.step+1,sta});
					mark[x][y][sta] = 1;
				}
			}

			else if(map[x][y] >= 'a' && map[x][y] <= 'j')
			{
				add = map[x][y]-'a';
				if((sta & (1<<add)) == 0)//注意先判断是否已有这种钥匙,没有再加
                    sta += (1 << add);
				if(!mark[x][y][sta])
				{
					que.push( (struct node) {x,y,u.step+1,sta});
					mark[x][y][sta] = 1;
				}

			}
			else if(map[x][y] >= 'A' && map[x][y] <= 'J')
			{
				add = map[x][y] - 'A';
				if( (sta & (1<<add)) && !mark[x][y][sta])
				{
					que.push((struct node) {x,y,u.step+1,sta});
					mark[x][y][sta] = 1;
				}
			}
		}
	}
	printf("-1\n");
}

int main()
{
	while(~scanf("%d %d %d",&n,&m,&t))
	{
		for(int i = 1; i <= n; i++)
		{
			scanf("%s",map[i]+1);
			for(int j = 1; j <= m; j++)
			{
				if(map[i][j] == '@')
				{
					sx = i;
					sy = j;
				}
			}
		}
		bfs();
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值