λ¬Έμ
λ°±μ€ μ¨λΌμΈ μ μ§ - 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())
λ°μν
'π algorithm > boj' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
BOJ 5014 - μ€ννΈλ§ν¬ (0) | 2021.06.09 |
---|---|
BOJ 1389 - μΌλΉ λ² μ΄μ»¨μ 6λ¨κ³ λ²μΉ (0) | 2021.06.09 |
BOJ 10026 - μ λ‘μμ½ (0) | 2021.06.09 |
BOJ 3135 - λΌλμ€ (0) | 2021.06.09 |
BOJ 13410 - κ±°κΎΈλ‘ κ΅¬κ΅¬λ¨ (0) | 2021.06.08 |
π¬ λκΈ