迷宫问题II | ||||||
| ||||||
Description | ||||||
小z身处在一个迷宫中,小z每分钟可以走到上下左右四个方向的相邻格之一。迷宫中有一些墙和障碍物。 同时迷宫中也有一些怪兽,当小z碰到任意一个怪兽时,小z需要将怪兽消灭掉才可以离开此方格。但消灭 怪兽会花费一定的时间。现在小z想知道走出迷宫需要花费的最少时间。 | ||||||
Input | ||||||
输入第一行为组数T(T<=10)。 对于每组数据第一行为两个整数R和C(1<=R,C<=200)。以下R行每行有C个字符,即迷宫地图。 其中”#”代表墙和障碍物,”.”表示空地,[1~9]的数字代表此处有怪兽以及消灭此处的怪兽需要的时间. “Z”表示小z的起始位置,”W”表示迷宫出口。 对于每组数据保证起始位置和迷宫出口唯一。 | ||||||
Output | ||||||
对于每组数据,输出走出迷宫的最短时间(单位:分钟)。如果无法走出迷宫则输出”IMPOSSIBLE”。 | ||||||
Sample Input | ||||||
2 | ||||||
Sample Output | ||||||
5 IMPOSSIBLE | ||||||
Hint | ||||||
Author | ||||||
陈禹@HRBUST |
和前面坦克大战的题一样,无非就是怪物浪费的步数不相同,但是不影响做,反正是优先队列。
代码如下:
#include <stdio.h>
#include <algorithm>
#include <queue>
using namespace std;
char map[211][211];
int strx,stry;
int endx,endy;
int w,h;
int mx[4]={0,0,1,-1};
int my[4]={1,-1,0,0};
int check(int x,int y) //返回1时不能移动
{
if (x<0 || x>=h || y<0 || y>=w || map[x][y]=='#')
return 1;
return 0;
}
struct node
{
int x,y,stp;
bool friend operator<(node a,node b)
{
return a.stp>b.stp;
}
}a,b;
int bfs()
{
priority_queue<node> move;
a.x=strx;
a.y=stry;
a.stp=0;
map[strx][stry]='#';
move.push(a);
while (!move.empty())
{
a=move.top();
move.pop();
if (a.x==endx && a.y==endy)
return a.stp;
for (int i=0;i<=3;i++)
{
b.x=a.x+mx[i];
b.y=a.y+my[i];
if (check(b.x,b.y))
continue;
b.stp=a.stp;
if (map[b.x][b.y]=='.')
b.stp++;
else if (map[b.x][b.y]=='W')
b.stp++;
else
b.stp+=map[b.x][b.y]-'0'+1;
map[b.x][b.y]='#';
move.push(b);
}
}
return -1;
}
int main()
{
int u;
int ans;
scanf ("%d",&u);
while (u--)
{
scanf ("%d%d",&h,&w);
for (int i=0;i<h;i++)
{
scanf ("%s",map[i]);
for (int j=0;j<w;j++)
{
if (map[i][j]=='Z')
{
strx=i;
stry=j;
}
else if (map[i][j]=='W')
{
endx=i;
endy=j;
}
}
}
ans=bfs();
if (ans==-1)
printf ("IMPOSSIBLE\n");
else
printf ("%d\n",ans);
}
return 0;
}
蓝鸟脑袋里的坑要填填了,那么水的错误23333