诡异的楼梯
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/65536 K (Java/Others)Total Submission(s): 12107 Accepted Submission(s): 2988
Problem Description
Hogwarts正式开学以后,Harry发现在Hogwarts里,某些楼梯并不是静止不动的,相反,他们每隔一分钟就变动一次方向.
比如下面的例子里,一开始楼梯在竖直方向,一分钟以后它移动到了水平方向,再过一分钟它又回到了竖直方向.Harry发现对他来说很难找到能使得他最快到达目的地的路线,这时Ron(Harry最好的朋友)告诉Harry正好有一个魔法道具可以帮助他寻找这样的路线,而那个魔法道具上的咒语,正是由你纂写的.
比如下面的例子里,一开始楼梯在竖直方向,一分钟以后它移动到了水平方向,再过一分钟它又回到了竖直方向.Harry发现对他来说很难找到能使得他最快到达目的地的路线,这时Ron(Harry最好的朋友)告诉Harry正好有一个魔法道具可以帮助他寻找这样的路线,而那个魔法道具上的咒语,正是由你纂写的.
Input
测试数据有多组,每组的表述如下:
第一行有两个数,M和N,接下来是一个M行N列的地图,'*'表示障碍物,'.'表示走廊,'|'或者'-'表示一个楼梯,并且标明了它在一开始时所处的位置:'|'表示的楼梯在最开始是竖直方向,'-'表示的楼梯在一开始是水平方向.地图中还有一个'S'是起点,'T'是目标,0<=M,N<=20,地图中不会出现两个相连的梯子.Harry每秒只能停留在'.'或'S'和'T'所标记的格子内.
第一行有两个数,M和N,接下来是一个M行N列的地图,'*'表示障碍物,'.'表示走廊,'|'或者'-'表示一个楼梯,并且标明了它在一开始时所处的位置:'|'表示的楼梯在最开始是竖直方向,'-'表示的楼梯在一开始是水平方向.地图中还有一个'S'是起点,'T'是目标,0<=M,N<=20,地图中不会出现两个相连的梯子.Harry每秒只能停留在'.'或'S'和'T'所标记的格子内.
Output
只有一行,包含一个数T,表示到达目标的最短时间.
注意:Harry只能每次走到相邻的格子而不能斜走,每移动一次恰好为一分钟,并且Harry登上楼梯并经过楼梯到达对面的整个过程只需要一分钟,Harry从来不在楼梯上停留.并且每次楼梯都恰好在Harry移动完毕以后才改变方向.
注意:Harry只能每次走到相邻的格子而不能斜走,每移动一次恰好为一分钟,并且Harry登上楼梯并经过楼梯到达对面的整个过程只需要一分钟,Harry从来不在楼梯上停留.并且每次楼梯都恰好在Harry移动完毕以后才改变方向.
Sample Input
5 5 **..T **.*. ..|.. .*.*. S....
Sample Output
7地图如下:HintHint
如果使用普通队列,就要遍历所有情况,选出最小的情况,如果用优先队列,则不需要。
代码:
#include <cstdio>
#include <cstring>
#include <queue>
#define MAX 21
using namespace std;
int row, col, ans;
int fx[4][2] = {1,0,0,1,0,-1,-1,0};
char map[MAX][MAX];
int vis[MAX][MAX];
struct node
{
int x, y;
int step;
friend bool operator<(node a, node b)
{
return a.step > b.step;
}
} init;
bool check(node n)
{
if (n.x < 0 || n.x >= col || n.y < 0 || n.y >= row || map[n.y][n.x] == '*' || (vis[n.y][n.x] && vis[n.y][n.x] <= n.step))
return false;
return true;
};
int bfs(node init)
{
node curr, next;
priority_queue <node>Q;
Q.push(init);
vis[init.y][init.x] = 1;
while (!Q.empty())
{
curr = Q.top();
Q.pop();
if (map[curr.y][curr.x] == 'T')
return curr.step;
for (int i = 0; i < 4; i++)
{
next.x = curr.x + fx[i][0];
next.y = curr.y + fx[i][1];
next.step = curr.step + 1;
if (map[next.y][next.x] == '|')
{
if (next.x == curr.x && curr.step%2 )
next.step++; //y轴走,梯子不在|
if (next.y == curr.y && !curr.step%2 )
next.step++; //x轴走,梯子在|
next.x += fx[i][0], next.y += fx[i][1];
}
else if (map[next.y][next.x] == '-')
{
if (next.x == curr.x && !curr.step%2 )
next.step++; //y轴走,梯子在-
if (next.y == curr.y && curr.step%2 )
next.step++; //x轴走,梯子不在-
next.x += fx[i][0], next.y += fx[i][1];
}
if (!check(next)) continue;
vis[next.y][next.x] = next.step;
Q.push(next);
}
}
return -1;
}
int main()
{
while (scanf("%d %d", &row, &col) != EOF)
{
memset(vis, 0, sizeof(vis));
for (int i = 0; i < row; i++)
{
scanf("%s", map[i]);
for (int j = 0; j < col; j++)
{
if (map[i][j] == 'S')
{
init.x = j, init.y = i;
init.step = 0;
}
}
}
;
printf("%d\n", bfs(init));
}
return 0;
}