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

ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€ Level 3 - 단어 λ³€ν™˜

by HandHand 2021. 3. 1.

문제

ν”„λ‘œκ·Έλž˜λ¨ΈμŠ€ - 단어 λ³€ν™˜

풀이 κ³Όμ •

μ‹œμž‘ λ‹¨μ–΄μ—μ„œ λͺ©ν‘œ λ‹¨μ–΄λ‘œ λ³€ν˜•ν•˜λŠ” μ΅œλ‹¨ 경둜(λΉ„μš©)을 μ°ΎλŠ” λ¬Έμ œμž…λ‹ˆλ‹€.

각 λ‹¨μ–΄λŠ” μ΅œλŒ€ ν•œ 문자만 변경이 κ°€λŠ₯ν•˜κ³  주어진 λ¦¬μŠ€νŠΈμ— ν¬ν•¨λœ 단어일 κ²½μš°μ—λ§Œ ν•΄λ‹Ή λ‹¨μ–΄λ‘œ λ³€ν™˜μ„ μ‹œλ„ν•΄λ³Ό 수 μžˆμŠ΅λ‹ˆλ‹€.

λ”°λΌμ„œ 각 νƒμƒ‰λ§ˆλ‹€ λ‹¨μ–΄μ˜ 자리수λ₯Ό ν•˜λ‚˜μ”© νƒμƒ‰ν•˜μ—¬ a to z 쀑 λ³€ν™˜μ΄ κ°€λŠ₯ν•œ 단어가 μžˆλŠ”μ§€ λ”°μ Έμ€λ‹ˆλ‹€.

μ΄λ•Œ Python μ—μ„œλŠ” ord & chr λ₯Ό ν†΅ν•΄μ„œ 문자의 μ•„μŠ€ν‚€μ½”λ“œ 값을 ν™œμš©ν•  수 μžˆλŠ”λ° λ¬Έμžμ—΄μ„ μ‰½κ²Œ μ²˜λ¦¬ν•˜κΈ° μœ„ν•΄ ν™œμš©ν•˜μ˜€μŠ΅λ‹ˆλ‹€.

λ˜ν•œ μ€‘λ³΅λœ λ³€ν™˜μ„ ν”Όν•˜κΈ° μœ„ν•΄ visit 은 λ”•μ…”λ„ˆλ¦¬λ‘œ μ„ μ–Έν•˜μ—¬ λ¬Έμžμ—΄ ν•΄μ‹± 을 톡해 이미 λ³€ν™˜μ„ μ‹œλ„ν–ˆλ˜ 단어인지 효율적으둜 νŒλ‹¨ν•˜λ„λ‘ ν–ˆμŠ΅λ‹ˆλ‹€.

μ½”λ“œ


from collections import deque


def bfs(start, goal, words):
    q = deque()
    visit = dict.fromkeys(words, 0)

    q.append((start, 0))

    while q:
        here, cost = q.popleft()
        if here == goal:
            return cost

        # 각 자리λ₯Ό μˆœνšŒν•˜λ©° μ•ŒνŒŒλ²³ ν•˜λ‚˜λ₯Ό λ³€κ²½ν•΄ λ§Œλ“€ 수 μžˆλŠ” 단어λ₯Ό νƒμƒ‰ν•΄λ΄…λ‹ˆλ‹€.
        for i, c in enumerate(here):
            for j in range(ord('a'), ord('z')+1):
                if i != chr(j):
                    new_word = here[:i] + chr(j) + here[i+1:]
                    # μƒˆλ‘œ λ§Œλ“€μ–΄μ§„ 단어가 후보 λ¦¬μŠ€νŠΈμ— μ‘΄μž¬ν•œλ‹€λ©΄
                    if new_word in words and not visit[new_word]:
                        visit[new_word] = 1
                        q.append((new_word, cost + 1))

    return 0


def solution(begin, target, words):
    ans = bfs(begin, target, words)
    return ans
λ°˜μ‘ν˜•

πŸ’¬ λŒ“κΈ€