Primary school students Blue Bridge Cup Python Breakthrough | Strange Elevator

Learn Python from a baby! Record the questions in the Blue Bridge Cup Python learning and test preparation process, and record every moment.

Attach a summary post: Pupils Blue Bridge Cup Python Breakthrough | Summary_Blue Bridge Cup Python Elementary School Group_COCOgsta's Blog-CSDN Blog


【Description】

Hehe, one day I had a dream, dreaming of a very strange elevator. Elevators can be stopped on each floor of the building, and there is a number Ki (0≤Ki≤N) on the i-th floor (1≤i≤N). The elevator has only four buttons: open, close, up, down. The number of floors up and down is equal to the number on the current floor. Of course, if the requirements are not met, the corresponding button will be disabled. For example: 3,3,1,2,5 represent Ki (K1=3, K2=3,...), starting from the 1st floor. On the 1st floor, you can go to the 4th floor by pressing "up", but it doesn't work if you press "down", because there is no -2 floor. So, at least how many button presses are required to get from building A to building B?

【Enter description】

There are two lines in total.

The first line is three positive integers separated by spaces, representing N, A, B (1≤N≤200, 1≤A, B less than or equal to N).

The second line is N non-negative integers separated by spaces, representing Ki.

【Output description】

One line, that is, the minimum number of key presses, if it cannot be reached, then output -1.

【Sample input】

5 1 5

3 3 1 2 5

【Sample output】

3

【Code Explanation】

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)

【operation result】

5 1 5
3 3 1 2 5
3

Guess you like

Origin blog.csdn.net/guolianggsta/article/details/130722796