您的位置:首页 > 其它

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

2016-07-21 12:09 281 查看
原题链接: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: