牛客网 地下迷宫

牛客网 地下迷宫

题目描述
小青蛙有一天不小心落入了一个地下迷宫,小青蛙希望用自己仅剩的体力值P跳出这个地下迷宫。为了让问题简单,假设这是一个n*m的格子迷宫,迷宫每个位置为0或者1,0代表这个位置有障碍物,小青蛙达到不了这个位置;1代表小青蛙可以达到的位置。小青蛙初始在(0,0)位置,地下迷宫的出口在(0,m-1)(保证这两个位置都是1,并且保证一定有起点到终点可达的路径),小青蛙在迷宫中水平移动一个单位距离需要消耗1点体力值,向上爬一个单位距离需要消耗3个单位的体力值,向下移动不消耗体力值,当小青蛙的体力值等于0的时候还没有到达出口,小青蛙将无法逃离迷宫。现在需要你帮助小青蛙计算出能否用仅剩的体力值跳出迷宫(即达到(0,m-1)位置)。
输入描述:
输入包括n+1行:
第一行为三个整数n,m(3 <= m,n <= 10),P(1 <= P <= 100)
接下来的n行:
每行m个0或者1,以空格分隔
输出描述:
如果能逃离迷宫,则输出一行体力消耗最小的路径,输出格式见样例所示;如果不能逃离迷宫,则输出”Can not escape!”。 测试数据保证答案唯一

分析:典型的dfs,同时用stack记录路径,当到达出口时,作比较,选出消耗最小的路径。(但这题我无法在牛客网上通过,它说不能用numpy,搞得我很无语啊,不想改了,总之思路是对的,还是把代码贴上来吧。)

import numpy as np
import copy

def findExit(x, y, consumP):
    global n;global m; global P; global tmpP
    global mat; global go; global consume; global mark
    global res; global stack
    if(x == 0 and y == m - 1):
        if(consumP < tmpP): 
            tmpP = consumP
            res = copy.copy(stack)
            return
    for i in range(4):
        xt = x + go[i][0]
        yt = y + go[i][1]
        if(xt < 0 or xt > n - 1 or yt < 0 or yt > m - 1): continue
        if(consumP + consume[i] > P): continue
        if(mat[xt][yt] == 0): continue
        if(mark[xt][yt] == 1): continue
        mark[xt][yt] = 1
        stack.append([xt,yt])
        findExit(xt, yt, consumP + consume[i])
        mark[xt][yt] = 0
        stack.remove([xt,yt])


n, m, P = map(int, raw_input().split())
mat = np.zeros((n, m))#迷宫
mark = np.zeros((n, m))#标记该路口是否已经过
mark[0][0] == 1
consume = [1,1,3,0]#消耗的体力值
go = np.array([0,-1,0,1,-1,0,1,0])
go = go.reshape(4,2)#四个方向
tmpP = 1000#用于记录消耗最小时消耗的P
res = []#记录最终路径
stack = []#保存遍历过程中的路径
stack.append([0,0])

#获取迷宫输入
for i in range(n):
    s = map(int, raw_input().split())
    for j in range(m):
        mat[i][j] = s[j]


findExit(0,0,0)
if(len(res) <= 1): print 'Can not escape!'
else:
    print ','.join(str(key) for key in res)

猜你喜欢

转载自blog.csdn.net/qq_42522262/article/details/81712182