λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°
πŸƒ algorithm/boj

BOJ 2644 - μ΄Œμˆ˜κ³„μ‚°

by HandHand 2021. 6. 9.

문제

λ°±μ€€ 온라인 저지 - 2644번

풀이 κ³Όμ •

문제 쑰건을 톡해 각 μžμ‹μ€ 였직 ν•˜λ‚˜μ˜ λΆ€λͺ¨λ§Œ μ£Όμ–΄μ§€λ―€λ‘œ 사이클 μ—†λŠ” 무방ν–₯ κ·Έλž˜ν”„λ‘œ λ‚˜νƒ€λ‚Ό 수 μžˆμŠ΅λ‹ˆλ‹€.

λ”°λΌμ„œ 촌수λ₯Ό κ³„μ‚°ν•˜κ³  싢은 두 μ‚¬λžŒμ€‘ μž„μ˜λ‘œ ν•œλͺ…을 μ„ νƒν•œ λ’€ λ‹€λ₯Έ ν•œλͺ…에 λ„λ‹¬ν•˜λŠ” 거리λ₯Ό κ³„μ‚°ν•˜λ©΄ 닡을 ꡬ할 수 μžˆμŠ΅λ‹ˆλ‹€.

μ΄λ•Œ, 도달 κ°€λŠ₯μ„± μœ λ¬΄λŠ” DFS λ₯Ό 톡해 κ³„μ‚°λœ 거리값을 톡해 μ•Œ 수 μžˆλ„λ‘ ν•˜μ˜€μŠ΅λ‹ˆλ‹€.

μ½”λ“œ


import sys

n = int(input())
target = list(map(int, sys.stdin.readline().split()))
m = int(input())
adj = [[] for _ in range(n+1)]
for _ in range(m):
    frm, to = list(map(int, sys.stdin.readline().split()))
    adj[frm].append(to)
    adj[to].append(frm)


def dfs(here, cost, visit):
    if here == target[1]:
        return cost

    visit.append(here)

    for near in adj[here]:
        if near not in visit:
            dist = dfs(near, cost+1, visit)
            if dist != -1:
                return dist
    return -1


def solution():
    visit = []
    ans = dfs(target[0], 0, visit)
    return ans


print(solution())
λ°˜μ‘ν˜•

πŸ’¬ λŒ“κΈ€