[백준] #1240 노드사이의 거리 python

2023. 5. 26. 11:04

https://www.acmicpc.net/problem/1240

 

1240번: 노드사이의 거리

N(2≤N≤1,000)개의 노드로 이루어진 트리가 주어지고 M(M≤1,000)개의 두 노드 쌍을 입력받을 때 두 노드 사이의 거리를 출력하라.

www.acmicpc.net

 

 

📕 설명 📕

python의 list로 구현하여서 트리를 구성하였다.

 

dfs를 이용하여 구현하였다.

 

노드 사이의 연결을 dfs로 오랜만에 써보려니 잘 써지지 않았다.

 

계속 복습해줘야지....

 

sys.setrecursionlimit(10**9) 도 까먹었다.. ㅠ

 

 

🧑🏻‍💻 나의 풀이 🧑🏻‍💻

import sys
sys.setrecursionlimit(10**9)


def dfs(start, end, distance):
    global count
    if start == end:
        count = distance
        return

    for node, val in tree[start]:
        if not visit[node]:
            visit[node] = True
            dfs(node, end, distance + val)


if __name__ == '__main__':
    N, M = map(int, input().split())
    tree = [[] for _ in range(N+1)]

    for i in range(N-1):
        a, b, c = map(int, input().split())
        tree[a].append([b, c])
        tree[b].append([a, c])

    for i in range(M):
        a, b = map(int, input().split())
        visit = [False] * (N + 1)
        count = 0
        visit[a] = True

        dfs(a, b, 0)
        print(count)

BELATED ARTICLES

more