Problem Description
Hogwarts正式开学以后,Harry发现在Hogwarts里,某些楼梯并不是静止不动的,相反,他们每隔一分钟就变动一次方向.
比如下面的例子里,一开始楼梯在竖直方向,一分钟以后它移动到了水平方向,再过一分钟它又回到了竖直方向.Harry发现对他来说很难找到能使得他最快到达目的地的路线,这时Ron(Harry最好的朋友)告诉Harry正好有一个魔法道具可以帮助他寻找这样的路线,而那个魔法道具上的咒语,正是由你纂写的.
Input
测试数据有多组,每组的表述如下:
第一行有两个数,M和N,接下来是一个M行N列的地图,’*‘表示障碍物,’.‘表示走廊,’|‘或者’-‘表示一个楼梯,并且标明了它在一开始时所处的位置:’|‘表示的楼梯在最开始是竖直方向,’-'表示的楼梯在一开始是水平方向.地图中还有一个’S’是起点,‘T’是目标,0<=M,N<=20,地图中不会出现两个相连的梯子.Harry每秒只能停留在’.'或’S’和’T’所标记的格子内.
Output
只有一行,包含一个数T,表示到达目标的最短时间.
注意:Harry只能每次走到相邻的格子而不能斜走,每移动一次恰好为一分钟,并且Harry登上楼梯并经过楼梯到达对面的整个过程只需要一分钟,Harry从来不在楼梯上停留.并且每次楼梯都恰好在Harry移动完毕以后才改变方向.
Sample Input
5 5
**…T
**..
…|…
..*.
S…
Sample Output
7
Hint
Hint
地图如下:
思路
这道题难度还是有一点的,主要是怎么判断人走到楼梯面前是能通过还是不能通过,楼梯会旋转应该假设走完一步之后楼梯立马旋转一个方向。最开始楼梯有两种,第一种是横着,第二种是竖着的。所以处理起来也是不一样的。
- 要判断楼梯对面能不能走,有些楼梯走过去就墙上或者出去了也是不行的。
- 当前走到楼梯面前不能通过可以原地等一分钟等楼梯换个方向就可以过去了。有点小坑,当时没想到WA了一发,一定要采用优先队列维护最短的时间。
挺好的一道题。
#include <iostream>
#include <cstring>
#include <algorithm>
#include <string>
#include <queue>
using namespace std;
const int maxn = 25;
struct Node{
int x,y,step;
bool operator < (const Node &s)const{
return s.step < step;
}
};
priority_queue<Node>q;
char map[maxn][maxn];
int visited[maxn][maxn];
int dx[] = {1,-1,0,0};
int dy[] = {0,0,1,-1};
int m,n;
void new_set()
{
while(!q.empty()){
q.pop();
}
memset(visited,0,sizeof(visited));
}
bool check(int x,int y)
{
if(x < 0 || x >= m || y < 0 || y >= n || map[x][y] == '*' || visited[x][y] == 1){
return false;
}
else{
return true;
}
}
void bfs()
{
Node p,ptr;
while(!q.empty()){
p = q.top();
q.pop();
if(map[p.x][p.y] == 'T'){
cout<<p.step<<endl;
break;
}
for(int i = 0;i < 4;i++){
ptr.x = p.x + dx[i];
ptr.y = p.y + dy[i];
if(check(ptr.x,ptr.y) == false){
continue;
}
if((map[ptr.x][ptr.y] == '|' && p.step % 2 == 0)
|| (map[ptr.x][ptr.y] == '-' && p.step % 2 == 1)){
if(dx[i] != 0){
ptr.x += dx[i];
ptr.y += dy[i];
if(check(ptr.x,ptr.y) == false){
continue;
}
ptr.step = p.step + 1;
visited[ptr.x][ptr.y] = 1;
q.push(ptr);
}
else{ //原地等一分钟等楼梯换个方向
ptr.x = p.x;
ptr.y = p.y;
ptr.step = p.step + 1;
q.push(ptr);
}
}
else if((map[ptr.x][ptr.y] == '|' && p.step % 2 == 1)
|| (map[ptr.x][ptr.y] == '-' && p.step % 2 == 0)){
if(dy[i] != 0){
ptr.x += dx[i];
ptr.y += dy[i];
if(check(ptr.x,ptr.y) == false){
continue;
}
ptr.step = p.step + 1;
visited[ptr.x][ptr.y] = 1;
q.push(ptr);
}
else{· //原地等一分钟等楼梯换个方向
ptr.x = p.x;
ptr.y = p.y;
ptr.step = p.step + 1;
q.push(ptr);
}
}
else{
visited[ptr.x][ptr.y] = 1;
ptr.step = p.step + 1;
q.push(ptr);
}
}
}
}
int main()
{
int x,y;
while(cin>>m>>n){
for(int i = 0;i < m;i++){
for(int j = 0;j < n;j++){
cin>>map[i][j];
if(map[i][j] == 'S'){
x = i;y = j;
}
}
}
new_set();
Node start;
start.x = x;start.y = y;start.step = 0;
q.push(start);
visited[x][y] = 1;
bfs();
}
return 0;
}
愿你走出半生,归来仍是少年~