链接:https://www.nowcoder.com/acm/contest/105/F
来源:牛客网
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
64bit IO Format: %lld
题目描述
小明来到一个由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
代码
#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <algorithm>
#include <bitset>
#include <queue>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
const int N = (int) 500 + 11;
const int M = (int) 1e5 + 11;
const int mod = (int) 1e9 + 7;
const int INF = 0X3F3F3F3F;
struct Node{
int x, y, step;
Node(){}
Node(int _x, int _y, int _step){
x = _x; y = _y; step = _step;
}
friend bool operator < (Node a, Node b){
return a.step > b.step;
}
};
int n, m, q;
int to[4][2] ={1, 0, -1, 0, 0, 1, 0, -1};
char mp[N + 1][N + 1]; int dis[N + 1][N + 1];
vector <pii> ve[M + 1];
int getid(int x, int y) { return x * m + y; }
void init(){
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
ve[getid(i, j)].clear();
}
}
}
int BFS(Node st){
memset(dis, 0x3f, sizeof(dis));
//printf("%d \n", dis[0][0]);
priority_queue <Node>Q;
Q.push(st);
while(!Q.empty()){
Node now = Q.top(); Q.pop();
if(mp[now.x][now.y] == 'T') return now.step;
for(int i = 0; i < 4; i++){
int nx = now.x + to[i][0]; int ny = now.y + to[i][1];
if(nx < 0 || nx >= n || ny < 0|| ny >= m || mp[nx][ny] == '#' || now.step + 1 >= dis[nx][ny]) continue;
dis[nx][ny] = now.step + 1;
Q.push(Node(nx, ny, now.step + 1));
}
int ID = getid(now.x, now.y);
for(int i = 0; i < ve[ID].size(); i++){
pii p = ve[ID][i];
int nx = p.first; int ny = p.second;
if(nx < 0 || nx >= n || ny < 0|| ny >= m || mp[nx][ny] == '#' || now.step + 3 >= dis[nx][ny]) continue;
dis[nx][ny] = now.step + 3;
Q.push(Node(nx, ny, now.step + 3));
}
}
return -1;
}
int main(){
while(scanf("%d%d%d", &n, &m, &q) != EOF){
init();
Node st;
for(int i = 0; i < n; i++){
scanf("%s", mp[i]);
for(int j = 0; j < m; j++){
if(mp[i][j] == 'S') {
st = Node(i, j, 0);
}
}
}
// printf(" ## %d %d %d \n", st.x, st.y, st.step);
while(q--){
int a, b, c, d;
scanf("%d%d%d%d", &a, &b, &c, &d);
if(mp[a][b] == '#' || mp[c][d] == '#') continue;
ve[getid(a, b)].push_back(make_pair(c, d));
}
printf("%d\n", BFS(st));
}
return 0;
}