hdu1429 胜利大逃亡(续)--BFS

原题链接:http://acm.hdu.edu.cn/showproblem.php?pid=1429


一:分析

定义一个三维数组,标记该点是否走过,其中第三维代表在该路径上所获钥匙的标记。


二:AC代码

#define _CRT_SECURE_NO_DEPRECATE 
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1 

#include<iostream>
#include<algorithm>
#include<queue>
#include<cctype>
using namespace std;

struct Node
{
	int x, y;
	int step;
	int state;
	Node(){}
	Node(int x, int y, int step, int state) :x(x), y(y), step(step), state(state) {}
};

int dir[4][2] = { { 0, 1 },{ 0, -1 },{ 1, 0 },{ -1, 0 } };
char s[25][25];
bool vis[25][25][1 << 10];
int n, m, t;

int get(char c)
{
	return c - (isupper(c) ? 'A' : 'a');
}

bool check(int x, int y)
{
	if (x < 0 || x >= n || y < 0 || y >= m || s[x][y] == '*')
		return false;
	return true;
}


int bfs(int x, int y)
{
	queue<Node> Q;
	vis[x][y][0] = 1;

	Q.push(Node(x, y, 0, 0));

	while (!Q.empty())
	{
		Node cur = Q.front();
		Q.pop();
		if (cur.step >= t - 1)
			break;

		for (int i = 0; i < 4; i++)
		{
			Node temp = cur;
			temp.x += dir[i][0];
			temp.y += dir[i][1];
			temp.step++;

			if (check(temp.x, temp.y) == 0 || vis[temp.x][temp.y][temp.state])
				continue;

			if (isupper(s[temp.x][temp.y]) && !(temp.state&(1 << get(s[temp.x][temp.y]))))//遇到门,没有钥匙,不走
				continue;

			if (islower(s[temp.x][temp.y]))//找到钥匙
				temp.state |= (1 << get(s[temp.x][temp.y]));
               
			if (s[temp.x][temp.y] == '^')
				return temp.step;

			if (!vis[temp.x][temp.y][temp.state])
			{
				vis[temp.x][temp.y][temp.state] = 1;
				Q.push(temp);
			}
		}
	}

	return -1;
}

int main()
{
	int x, y;
	while (~scanf("%d%d%d", &n, &m, &t))
	{
		for (int i = 0; i < n; i++)
		{
			getchar();
			for (int j = 0; j < m; j++)
			{
				scanf("%c", &s[i][j]);
				if (s[i][j] == '@')
				{
					x = i;
					y = j;
				}
			}
		}

		memset(vis, 0, sizeof(vis));

		printf("%d\n", bfs(x, y));
	}

	return 0;
}







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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值