[Programmers] λ¨μ΄ λ³ν
Updated:
λ¨μ΄ λ³ν
λ¨μ΄ λ³ν μ ν΄λ¦νλ©΄ λ°λ‘ μ΄λνλ€.
νμ¬ κΈ°μ€ λ¨μ΄μ ν κΈμλ§ λ€λ₯Έ λ¨μ΄λ€μ μ λΆ νμ λ£κ³ λΉΌλ©° μ°Ύκ³ μ νλ λ¨μ΄κ° λμ¬ λ κΉμ§ λ°λ³΅νλ©΄ λλ€.
λ§λ€ μ μλ κ²½μ°λ words μ λ¨μ΄κ° μλ κ²½μ°μ΄λ―λ‘ μ²μμ 체ν¬ν΄ μ€λ€.
ν κΈμλ§ λ€λ₯Έ λ¨μ΄λ₯Ό μ°ΎκΈ° μν΄ μ²μμ μ°¨μ§ν©μ μ¬μ©νμΌλ μκ°μ΄ 짧μλ€.
κ°μ λ¬Έμλ‘ μ΄λ£¨μ΄μ§ λ¨μ΄λΌλ©΄ μλ¬κ° λ°μνλ€.
λ°λΌμ zip μ ν΅ν΄ λμμ μννλ©° λΉκ΅λ₯Ό ν΄μ£Όμλ€.
from collections import deque
def is_another_one(pivot, check):
diff_cnt = 0
# λ¨μ΄λ₯Ό λΉκ΅ν΄ λ€λ₯Έ λΆλΆ κ°―μ κ²μ
for a, b in zip(pivot, check):
if a != b:
diff_cnt += 1
if diff_cnt != 1:
return False
else:
return True
def solution(begin, target, words):
# λ³νν μ μλ κ²½μ°
if target not in words:
return 0
queue = deque([])
# ν μ΄κΈ°ν
for word in words:
if is_another_one(begin, word):
queue.append([word, 1])
# BFS
while queue:
word, work = queue.popleft()
if word == target:
return work
for check in words:
if is_another_one(word, check):
queue.append([check, work + 1])
Leave a comment