小学生蓝桥杯Python闯关 | 奇怪的电梯

学习Python从娃娃抓起!记录下蓝桥杯Python学习和备考过程中的题目,记录每一个瞬间。

附上汇总贴:小学生蓝桥杯Python闯关 | 汇总_蓝桥杯python小学组_COCOgsta的博客-CSDN博客


【题目描述】

呵呵,有天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层都可以停电梯,而且第i层楼(1≤i≤N)上有一个数字Ki(0≤Ki≤N)。电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。例如:3,3,1,2,5代表了Ki(K1= 3,K2=3,...),从1楼开始。在1楼,按“上”可以到4楼,按“下”是不起作用的,因为没有-2楼。那么,从A楼到B楼至少要按几次按钮呢?

【输入描述】

共二行。

第一行为三个用空格隔开的正整数,表示N,A,B(1≤N≤200,1≤A,B小于等于N)。

第二行为N个用空格隔开的非负整数,表示Ki。

【输出描述】

一行,即最少按键次数,若无法到达,则输出-1。

【样例输入】

5 1 5

3 3 1 2 5

【样例输出】

3

【代码详解】

N, A, B = [int(i) for i in input().split()]

ele = [0]

[ele.append(int(i)) for i in input().split()]

res = 10000000
st = [0 for i in range(N + 1)]


def dfs(x, cnt):
    global res
    if cnt >= res: return

    if x == B:
        res = min(res, cnt)
        return

    # 上
    if x + ele[x] <= N and not st[x + ele[x]]:
        st[x + ele[x]] = True
        dfs(x + ele[x], cnt + 1)
        st[x + ele[x]] = False
    # 下
    if x - ele[x] > 0 and not st[x - ele[x]]:
        st[x - ele[x]] = True
        dfs(x - ele[x], cnt + 1)
        st[x - ele[x]] = False


dfs(1, 0)
if res == 10000000: print(-1)
print(res)

【运行结果】

5 1 5
3 3 1 2 5
3

猜你喜欢

转载自blog.csdn.net/guolianggsta/article/details/130722796
今日推荐