HDOJ-1429 胜利大逃亡(续)

来源:互联网 发布:全排列算法 详解 编辑:程序博客网 时间:2024/05/18 22:09
Problem Description
Ignatius再次被魔王抓走了(搞不懂他咋这么讨魔王喜欢)……

这次魔王汲取了上次的教训,把Ignatius关在一个n*m的地牢里,并在地牢的某些地方安装了带锁的门,钥匙藏在地牢另外的某些地方。刚开始Ignatius被关在(sx,sy)的位置,离开地牢的门在(ex,ey)的位置。Ignatius每分钟只能从一个坐标走到相邻四个坐标中的其中一个。魔王每t分钟回地牢视察一次,若发现Ignatius不在原位置便把他拎回去。经过若干次的尝试,Ignatius已画出整个地牢的地图。现在请你帮他计算能否再次成功逃亡。只要在魔王下次视察之前走到出口就算离开地牢,如果魔王回来的时候刚好走到出口或还未到出口都算逃亡失败。
 

Input
每组测试数据的第一行有三个整数n,m,t(2<=n,m<=20,t>0)。接下来的n行m列为地牢的地图,其中包括:

. 代表路
* 代表墙
@ 代表Ignatius的起始位置
^ 代表地牢的出口
A-J 代表带锁的门,对应的钥匙分别为a-j
a-j 代表钥匙,对应的门分别为A-J

每组测试数据之间有一个空行。
 

Output
针对每组测试数据,如果可以成功逃亡,请输出需要多少分钟才能离开,如果不能则输出-1。

【状态压缩】
 
#include<iostream>#include<string>#include<vector>#include<queue>using namespace std;int n, m, t;vector<string> graph;int visited[22][22][1026];int dx[4] = { -1, 0, 1, 0 };int dy[4] = { 0, 1, 0, -1 };struct point{int x;int y;int z;point() {}point(int x, int y, int z){this->x = x;this->y = y;this->z = z;}};int bfs(int sx, int sy, int sz){queue<point> q;q.push(point(sx, sy, sz));while (!q.empty()){point temp = q.front();q.pop();for (int i = 0; i < 4; i++){int x = temp.x + dx[i], y = temp.y + dy[i], z = temp.z;int dis = visited[temp.x][temp.y][temp.z];if (dis == t - 1)return -1;if (x >= 0 && x < n && y >= 0 && y < m && visited[x][y][z] == -1){if (graph[x][y] == '.' || graph[x][y] == '@'){q.push(point(x, y, z));visited[x][y][z] = dis + 1;}if (graph[x][y] == '^'){q.push(point(x, y, z));visited[x][y][z] = dis + 1;return visited[x][y][z];}if (graph[x][y] >= 'a' && graph[x][y] <= 'z'){int tt = graph[x][y] - 'a';z = z | (1 << tt);q.push(point(x, y, z));visited[x][y][z] = dis + 1;}if (graph[x][y] >= 'A' && graph[x][y] <= 'Z'){int tt = graph[x][y] - 'A';if ((z & (1 << tt)) != 0){//z = z & (~(1 << tt));q.push(point(x, y, z));visited[x][y][z] = dis + 1;}}}}}return -1;}int main(){while (cin >> n >> m >> t){graph.clear();graph.resize(n);for (int i = 0; i < 22; i++)for (int j = 0; j < 22; j++)for (int k = 0; k < 1026; k++)visited[i][j][k] = -1;for (int i = 0; i < n; i++)cin >> graph[i];int sx = -1, sy = -1;for (int i = 0; i < n; i++){for (int j = 0; j < m; j++){if (graph[i][j] == '@'){sx = i;sy = j;visited[i][j][0] = 0;break;}}}cout << bfs(sx, sy, 0) << endl;}}


0 0
原创粉丝点击