다익스트라 알고리즘 (Python) 재귀함수 [코딩테스트]



# 총 거리비용과 거쳐간 노드에 관한 배열을 참조하는 재귀함수
def recursive_cost(node, to_arr, from_v, fin, cost_arr, pre_cost = 0):
    for i in range(0, len(to_arr)):
        if (not node[from_v].get(to_arr[i])):
            continue

        if (to_arr[i] == fin):
            new_cost = get_cost(node, to_arr[i], from_v) + pre_cost
            cost_arr.append( new_cost )
        else:
            tmp = to_arr.copy()
            tmp.remove(to_arr[i])
            new_cost = get_cost(node, to_arr[i], from_v) + pre_cost
            recursive_cost(node, tmp, to_arr[i], fin, cost_arr, new_cost)
            
        new_cost = 0

# 거리비용 리턴
def get_cost(node, to_v, from_v):
    if (node[from_v].get(to_v)):
        return node[from_v].get(to_v)
    else:
        return float('inf')

# 간선 갱신 or 추가
def update_node(node, from_v, to_v, cost):
    if ( node[from_v].get(to_v) and node[from_v][to_v] > cost ):
        node[from_v].update({to_v: cost}) # 최소거리 간선인 경우 갱신
    elif( not node[from_v].get(to_v) ):
        node[from_v].update({to_v: cost}) # 간선 추가

n, e = list( map(int, input().split(' ')) ) # (노드수 간선수) 형식으로 입력받기
node = {}

for i in range(0, e):
    arr1 = list( map(int, input().split(' ')) ) # (노드1 노드2 코스트) 형식으로 입력받기
    if node.get(arr1[0]): # 해당 노드가 있는 경우
        update_node(node, arr1[0], arr1[1], arr1[2])
        if node.get(arr1[1]):
            update_node(node, arr1[1], arr1[0], arr1[2])
        else:
            node[arr1[1]] = {arr1[0]: arr1[2]} # 최초 해당 노드값이 없는 경우
    else: # 해당 노드가 없는 경우 (최초)
        node[arr1[0]] = {arr1[1]: arr1[2]} # 최초 해당 노드값이 없는 경우
        if node.get(arr1[1]):
            update_node(node, arr1[1], arr1[0], arr1[2])
        else:
            node[arr1[1]] = {arr1[0]: arr1[2]} # 최초 해당 노드값이 없는 경우

start = int(input()) # 시작지점 입력받기
to_arr = list(node.keys())
to_arr.remove(start) # 시작 노드를 제외한 노드

for fin in range(1, n+1):
    cost_arr = []
    if (start == fin):
        print("{}: {}".format(fin, 0))
        continue
    
    recursive_cost(node, to_arr, start, fin, cost_arr, 0)
    print( "{}: {}".format(fin, min(cost_arr)) )

--- #### 예시1 _입력_ ``` 3 4 1 2 5 1 3 4 2 3 2 2 3 1 1 ``` _출력_ ``` 1: 0 2: 5 3: 4 ``` #### 예시2 _입력_ ``` 4 4 1 2 3 1 3 2 2 1 5 3 4 3 2 ``` _출력_ ``` 1: 3 2: 0 3: 5 4: 8 ```
되돌아가기 수정