Problem K.僵尸又来了
时限:1000ms 内存限制:10000K 总时限:3000ms
描述
由于聪明的佳佳很善于布置花园,所以僵尸没能在天亮之前冲到佳佳家里,这次僵尸又要来佳佳家做客了,佳佳很高兴,因为姑妈送给佳佳的大嘴花派上了用场。你拿到了花园的地图(以二维矩阵的形式表示)以及起点和佳佳家的位置。花园里一个位置有大嘴花,僵尸到达时会被吃掉,同时从起点又会出来一个新的僵尸,如果僵尸到达大嘴花的位置时,前一个僵尸还没有吃完,大嘴花将被吃掉,看看僵尸能否在天亮前到达佳佳家里?能的话,最少花费多少时间。
输入
输入的第一行包含4个整数:m,n,t, p。代表m行n列的地图、大嘴花吃掉僵尸花费的时间t和距离天亮的时间p。m,n都是小于200的正整数,t是小于10的正整数,第2行开始的m行是m行n列的花园地图,其中!代表起点,+表示佳佳家。*代表通路,@代表大嘴花,#表示墙。
输出
输出僵尸到达佳佳家最少需要花费的时间。如果在天亮之前无法到达,则输出-1。
输入样例
4 4 5 50
#!##
**##
**#+
***@
输出样例
-1
#include <iostream>
#include <queue>
using namespace std;
struct rec {
int x, y;
int useful;
int time;
};
queue<rec> q;
rec st, ed, chomper;
int m, n, t, p, more;
int visited[201][201];
char maze[200][200];
int dx[4] = {0, 0, -1, 1};
int dy[4] = {-1, 1, 0, 0};
void init() {
cin >> m >> n >> t >> p;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> maze[i][j];
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (maze[i][j] == '!') {
st.x = i, st.y = j;
}
if (maze[i][j] == '@') {
chomper.x = i, chomper.y = j;
}
if (maze[i][j] == '+') {
ed.x = i, ed.y = j;
}
}
}
st.time = 0;
}
rec moveto(rec now, int i) {
rec next;
next.x = now.x + dx[i];
next.y = now.y + dy[i];
if (next.x >= m || next.x < 0 || next.y >= n || next.y < 0 || maze[next.x][next.y] == '#') { //位置不合法
next.useful = false;
return next;
}
next.useful = true;
return next;
}
int bfs1() {
q.push(st);
while (q.size()) {
rec now = q.front();
if (now.x == chomper.x && now.y == chomper.y && now.time >= t) {
return -1;
}
if (now.time > p) {
return -1;
}
if (now.x == ed.x && now.y == ed.y) {
return now.time;
}
if (now.x == chomper.x && now.y == chomper.y) {
more = now.time;
}
q.pop();
for (int i = 0; i < 4; i++) {
rec next = moveto(now, i);
if (next.useful == true && !visited[next.x][next.y]) {
visited[next.x][next.y] = 1;
next.time = now.time + 1;
q.push(next);
}
}
}
return -1;
}
int bfs2() {
q.push(st);
while (q.size()) {
rec now = q.front();
if (now.x == ed.x && now.y == ed.y) {
return now.time;
}
q.pop();
for (int i = 0; i < 4; i++) {
rec next = moveto(now, i);
if (next.useful == true && !visited[next.x][next.y] && maze[next.x][next.y] != '@') {
visited[next.x][next.y] = 1;
next.time = now.time + 1;
q.push(next);
}
}
}
return -1;
}
int main() {
init();
int ans1 = bfs1();
memset(visited, 0, sizeof(visited));
while (q.size()) {
q.pop();
}
int ans2 = bfs2();
if (ans2 != -1 && ans1 != -1) {
cout << min(ans2, ans1 + more) << endl;
} else if (ans2 == -1 && ans1 != -1) {
cout << ans1 + more << endl;
} else if (ans1 == -1 && ans2 != -1) {
cout << ans2 << endl;
} else {
cout << -1 << endl;
}
return 0;
}