简单的bfs。题意是从某个点出发,问怎样才能最快走到出口。其中 . 代表空地,@代表桥,每座吊桥首先要放下来,这个过程需要D时间,然后过桥再消耗单位时间。
这里的小技巧是需要用到结构体priority_queue。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#define SIZE 512
using namespace std;
struct node
{
int x,y,step;
friend bool operator < (const node &a, const node &b)
{
return a.step > b.step;
}
};
char map[SIZE][SIZE];
bool vis[SIZE][SIZE];
int T,H,W,D,sx,sy,ex,ey;
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
priority_queue <node> Q;
int ans;
int bfs()
{
node fir,nex;
while(!Q.empty())
Q.pop();
fir.x = sx, fir.y = sy, fir.step = 1;
vis[sx][sy] = true;
Q.push(fir);
while(!Q.empty())
{
fir = Q.top();
Q.pop();
if(fir.x == ex && fir.y == ey)
return fir.step;
for(int i=0; i<4; i++)
{
nex.x = fir.x + dir[i][0];
nex.y = fir.y + dir[i][1];
if(!vis[nex.x][nex.y] && map[nex.x][nex.y] != '#' &&
nex.x >= 1 && nex.x <= H && nex.y >= 1 && nex.y <= W)
{
vis[nex.x][nex.y] = true;
if(map[nex.x][nex.y] == '.')nex.step = fir.step + 1;
else nex.step = fir.step + D + 1;
Q.push(nex);
}
}
}
return 0;
}
int main()
{
scanf("%d",&T);
while(T--)
{
scanf("%d%d%d",&H,&W,&D);
for(int i=1; i<=H; i++)
{
for(int j=1; j<=W; j++)
{
cin >> map[i][j];
if(map[i][j] == 'S')
{
sx = i, sy = j;
map[i][j] = '.';
}
if((map[i][j] == '.' || map[i][j] == '@') && (i == H || j == W || i == 1 || j == 1))
ex = i, ey = j;
}
}
memset(vis,0,sizeof(vis));
int ans = bfs();
printf("%d\n",ans);
}
return 0;
}