链接:https://www.nowcoder.com/acm/contest/105/F
来源:牛客网
题目描述
小明来到一个由n x m个格子组成的迷宫,有些格子是陷阱,用’#’表示,小明进入陷阱就会死亡,’.’表示没有陷阱。小明所在的位置用’S’表示,目的地用’T’表示。
小明只能向上下左右相邻的格子移动,每移动一次花费1秒。
有q个单向传送阵,每个传送阵各有一个入口和一个出口,入口和出口都在迷宫的格子里,当走到或被传送到一个有传送阵入口的格子时,小明可以选择是否开启传送阵。如果开启传送阵,小明就会被传送到出口对应的格子里,这个过程会花费3秒;如果不开启传送阵,将不会发生任何事情,小明可以继续向上下左右四个方向移动。
一个格子可能既有多个入口,又有多个出口,小明可以选择任意一个入口开启传送阵。使用传送阵是非常危险的,因为有的传送阵的出口在陷阱里,如果小明使用这样的传送阵,那他就会死亡。也有一些传送阵的入口在陷阱里,这样的传送阵是没有用的,因为小明不能活着进入。请告诉小明活着到达目的地的最短时间。
输入描述:
有多组数据。对于每组数据:
第一行有三个整数n,m,q(2≤ n,m≤300,0≤ q ≤ 1000)。
接下来是一个n行m列的矩阵,表示迷宫。
最后q行,每行四个整数x1,y1,x2,y2(0≤ x1,x2< n,0≤ y1,y2< m),表示一个传送阵的入口在x1行y1列,出口在x2行y2列。
输出描述:
如果小明能够活着到达目的地,则输出最短时间,否则输出-1。
示例1
输入
5 5 1
..S..
.....
.###.
.....
..T..
1 2 3 3
5 5 1
..S..
.....
.###.
.....
..T..
3 3 1 2
5 5 1
S.#..
..#..
###..
.....
....T
0 1 0 2
4 4 2
S#.T
.#.#
.#.#
.#.#
0 0 0 3
2 0 2 2
输出
6
8
-1
3
题意:
给你一个迷宫,求走到出口最短时间。还是四个方向,每一步一秒,特别的就是有个传送矩阵,能从一个点传送到另一个点,花费三秒。
首先整个框架是个广搜,因为加入队列的时间并不是递增的(传送要3秒,而直接走只要一秒),而我们要求最小值,就需要让时间小的优先取出,这时候就用到优先队列(把加入队列的按时间小值优先)了;
放入队列早并不代表时间短,也不代表一定会走这个点,所以放入队列时先不标记,在取出队列时再判断是否用过并标记,和判断是否是终点。
#include <iostream>
#include <cstring>
#include <queue>
#include <map>
#include <vector>
#define ll long long
using namespace std;
int n, m, p, v[320][320];
char ma[320][320];
struct node {
int x, y, t;
bool operator < (const node &a) const {
return t > a.t;//最小值优先
}
} no, ne, st, en;
vector<node> ch[305][305];
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
int judge(int x, int y) {
if (x < 0 || x >= n || y < 0 || y >= m || ma[x][y] == '#')
return 0;
return 1;
}
int bfs() {
priority_queue <node> q;
memset(v, 0, sizeof(v));
q.push(st);
while (!q.empty()) {
no = q.top();
q.pop();
if (no.x == en.x && no.y == en.y)
return no.t;
if (v[no.x][no.y])
continue;
v[no.x][no.y] = 1;
for (int i = 0; i < 4; i++) {
ne.x = no.x + dx[i];
ne.y = no.y + dy[i];
ne.t = no.t + 1;
if (judge(ne.x, ne.y))
q.push(ne);
}
for (int i = 0; i < ch[no.x][no.y].size(); i++) {
ne = ch[no.x][no.y][i];
ne.t = no.t + 3;
if (judge(ne.x, ne.y))
q.push(ne);
}
}
return -1;
}
int main() {
while (~scanf("%d%d%d", &n, &m, &p)) {
for (int i = 0; i < 305; i++) {//清空vector
for (int j = 0; j < 305; j++) {
ch[i][j].clear();
}
}
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
scanf(" %c", &ma[i][j]);
if (ma[i][j] == 'S')
st.x = i, st.y = j, st.t = 0;
else if (ma[i][j] == 'T')
en.x = i, en.y = j;
}
int x1, x2, y1, y2;
for (int i = 0; i < p; i++) {
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
ne.x = x2, ne.y = y2;
ch[x1][y1].push_back(ne);
}
printf("%d\n", bfs());
}
return 0;
}