Zerojudge. j124 石窟探險

題解

從第一個點開始一直往下遞迴。遇到偶數就是往右取兩個,遇到奇數就是往下取三個。

Python 解答

def DFS(i):
    global index, result
    nx = seq[index]
    index +=1
    
    if nx==0:
        return  #不再往下拿index, 繼續取資料
    else:
        for _ in range(2+nx%2):
            DFS(nx)
        
        result += abs(i-nx)
        return 

seq    = list(map(int, input().split()))
index  = 0 #控制index位置來拿資料後,判斷後,再往下呼叫
result = 0
DFS(seq[index])
print(result)