Hero In Maze

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lzyws739307453/article/details/80445111

Hero In Maze

时间限制: 1000 Sec   内存限制: 64 MB

题目描述

500年前,Jesse是我国最卓越的剑客。他英俊潇洒,而且机智过人^_^。
突然有一天,Jesse心爱的公主被魔王困在了一个巨大的迷宫中。Jesse听说这个消息已经是两天以后了,他知道公主在迷宫中还能坚持T天,他急忙赶到迷宫,开始到处寻找公主的下落。 时间一点一点的过去,Jesse还是无法找到公主。最后当他找到公主的时候,美丽的公主已经死了。从此Jesse郁郁寡欢,茶饭不思,一年后追随公主而去了。T_T 500年后的今天,Jesse托梦给你,希望你帮他判断一下当年他是否有机会在给定的时间内找到公主。
他会为你提供迷宫的地图以及所剩的时间T。请你判断他是否能救出心爱的公主。

输入

题目包括多组测试数据。 每组测试数据以三个整数N,M,T(0<n, m≤20, t>0)开头,分别代表迷宫的长和高,以及公主能坚持的天数。 紧接着有M行,N列字符,由".","*","P","S"组成。其中 "." 代表能够行走的空地。 "*" 代表墙壁,Jesse不能从此通过。 "P" 是公主所在的位置。 "S" 是Jesse的起始位置。 每个时间段里Jesse只能选择“上、下、左、右”任意一方向走一步。 输入以0 0 0结束。

输出

如果能在规定时间内救出公主输出“YES”,否则输出“NO”。

样例输入

4 4 10
....
....
....
S**P
0 0 0

样例输出

YES

解题思路

这道题用广搜,不能用深搜,深搜会时间超限。具体见代码:

#include <stdio.h>
#include <string.h>
struct note {
    int x, s, y;
}que[401];
int main() {
    char map[25][25];
    int t, n, m, p, q, vis[25][25];
    int next[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    while (scanf("%d %d %d", &n, &m, &t), n || m || t) {
        int tx, ty, head = 1, tail = 1, temp = 0;
        memset(vis, 0, sizeof(vis));
        for (int i = 1; i <= m; i++) {
            getchar();
            for (int j = 1; j <= n; j++) {
                scanf("%c", &map[i][j]);
                if (map[i][j] == 'S') {
                    que[tail].x = i;
                    que[tail].y = j;
                }
                if (map[i][j] == 'P') {
                    p = i;
                    q = j;
                }
            }
        }
        vis[que[tail].x][que[tail].y] = 1;
        que[tail++].s = 0;
        while (head < tail) {
            for (int k = 0; k < 4; k++) {
                tx = que[head].x + next[k][0];
                ty = que[head].y + next[k][1]; 
                if (tx < 1 || ty < 1 || tx > m || ty > n)
                    continue;
                if (!vis[tx][ty] && map[tx][ty] != '*') {
                    vis[tx][ty] = 1;
                    que[tail].x = tx;
                    que[tail].y = ty;
                    que[tail++].s = que[head].s + 1;
                }
                if (tx == p && ty == q) {
                    temp = 1;
                    break;
                }
            }
            if (temp)
                break;
            head++;
        }
        if (que[tail - 1].s <= t && temp)
            puts("YES");
        else puts("NO");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/lzyws739307453/article/details/80445111