Skip to content

Commit

Permalink
feat : 노드사이의 거리 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
jeeminimini committed Nov 11, 2023
1 parent 48d44af commit 7ca7256
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions src/main/kotlin/jimin/49week/노드사이의 거리.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
'''
bfs를 이용해서 거리를 탐색함
'''

import sys
from collections import deque

n, m = map(int, sys.stdin.readline().split())
INF = 10_001
nodes = [[] for _ in range(n + 1)]

for i in range(n - 1):
a, b, d = map(int, sys.stdin.readline().split())
nodes[a].append([b, d])
nodes[b].append([a, d])

def findDistance(a, b):
global n, m
queue = deque([[a, 0]])
visited = [0 for _ in range(n + 1)]
visited[0] = 1
visited[a] = 1
result = 0

while queue:
now, num = queue.popleft()

if now == b:
result = num
break

for next, dis in nodes[now]:
if not visited[next]:
queue.append([next, dis + num])
visited[next] = 1

return result


for i in range(m):
a, b = map(int, sys.stdin.readline().split())
result = findDistance(a, b)
print(result)

0 comments on commit 7ca7256

Please sign in to comment.