地牢逃脱-python


题目描述

给定一个 n 行 m 列的地牢,其中 ‘.’ 表示可以通行的位置,’X’ 表示不可通行的障碍,牛牛从 (x0 , y0 ) 位置出发,遍历这个地牢,和一般的游戏所不同的是,他每一步只能按照一些指定的步长遍历地牢,要求每一步都不可以超过地牢的边界,也不能到达障碍上。地牢的出口可能在任意某个可以通行的位置上。牛牛想知道最坏情况下,他需要多少步才可以离开这个地牢。


输入描述

每个输入包含 1 个测试用例。每个测试用例的第一行包含两个整数 n 和 m(1 <= n, m <= 50),表示地牢的长和宽。接下来的 n 行,每行 m 个字符,描述地牢,地牢将至少包含两个 ‘.’。接下来的一行,包含两个整数 x0, y0,表示牛牛的出发位置(0 <= x0 < n, 0 <= y0 < m,左上角的坐标为 (0, 0),出发位置一定是 ‘.’)。之后的一行包含一个整数 k(0 < k <= 50)表示牛牛合法的步长数,接下来的 k 行,每行两个整数 dx, dy 表示每次可选择移动的行和列步长(-50 <= dx, dy <= 50)


输出描述

输出一行一个数字表示最坏情况下需要多少次移动可以离开地牢,如果永远无法离开,输出 -1。以下测试用例中,牛牛可以上下左右移动,在所有可通行的位置.上,地牢出口如果被设置在右下角,牛牛想离开需要移动的次数最多,为3次。


示例1

输入

            3 3
            ...
            ...
            ...
            0 1
            4
            1 0
            0 1
            -1 0
            0 -1

输出

            3

代码


#一定要用广度优先的算法来,题目意思描述的不是那么明显,但是可以从上面那个示例看出要用广度优先解析
(x,y)=[int(i) for i in raw_input("").split()]
data=[]
for i in range(x):
    data.append(list(raw_input("")))
(startx,starty)=[int(i) for i in raw_input("").split()]
k=int(raw_input(""))
skip_step=[]
for index in range(k):
    skip_step.append([int(i) for i in raw_input("").split()])

visitied=[[0 for s in range(y)] for p in range(x)]
cost=[[0 for s in range(y)] for p in range(x)]
datalist=[]
datalist.append([startx,starty])
visitied[startx][starty]=1
def count_max():
    while datalist!=[]:
        (sx,sy)=datalist.pop(0)

        for stepx,stepy in skip_step:
            new_x=stepx+sx
            new_y=stepy+sy
            if new_x >= 0  and  new_x < x and new_y >= 0 and new_y < y and data[new_x][new_y] == "." and visitied[new_x][new_y]==0:
                visitied[new_x][new_y]=1
                cost[new_x][new_y]=cost[sx][sy]+1
                datalist.append([new_x,new_y])
count_max()
max_value=0
mark_unreachable=0



for index_i in range(x):
    for index_j in range(y):
        if data[index_i][index_j]==".":
            if cost[index_i][index_j]==0 and (index_i!=startx or index_j!=starty):
                mark_unreachable=1
            else:
                max_value=max(max_value,cost[index_i][index_j])
if mark_unreachable==1:
    print -1
else:
    print max_value
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值