ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๋‹จ์–ด ๋ณ€ํ™˜

๋‘ ๊ฐœ์˜ ๋‹จ์–ด begin, target๊ณผ ๋‹จ์–ด์˜ ์ง‘ํ•ฉ words๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. ์•„๋ž˜์™€ ๊ฐ™์€ ๊ทœ์น™์„ ์ด์šฉํ•˜์—ฌ begin์—์„œ target์œผ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ๊ฐ€์žฅ ์งง์€ ๋ณ€ํ™˜ ๊ณผ์ •์„ ์ฐพ์œผ๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. 1. ํ•œ ๋ฒˆ์— ํ•œ ๊ฐœ์˜ ์•ŒํŒŒ๋ฒณ๋งŒ ๋ฐ”๊ฟ€ ์ˆ˜

programmers.co.kr

 

๋ฌธ์ œ ํ’€์ด

 ํŠน์ • ๋‹จ์–ด๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ, ๋‹ค๋ฅธ ๋‹จ์–ด์™€ ๋น„๊ตํ•˜์—ฌ ํ•˜๋‚˜๋งŒ ๋‹ค๋ฅธ ๊ฒฝ์šฐ์— ๊ทธ ๋‹จ์–ด๋กœ ๋ณ€ํ™˜ํ•  ์ˆ˜ ์žˆ๋‹ค. DSF๋ฅผ ํ†ตํ•ด ์ฒ˜์Œ ์‹œ์ž‘ํ•˜๋Š” ๋ฌธ์ž๋ถ€ํ„ฐ, ๋ณ€ํ™œ ํ•  ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ž์™€ ๋น„๊ตํ•˜์—ฌ ๋‘ ๋ฌธ์ž๊ฐ€ ํ•˜๋‚˜๋งŒ ๋‹ค๋ฅธ ๊ฒฝ์šฐ ํ•ด๋‹น ๋ฌธ์ž๋ฅผ ๊ธฐ์ค€์œผ๋กœ ํƒ์ƒ‰ํ•  ์ˆ˜ ์žˆ๋Š” ๊ณผ์ •์„ ๋ฐ˜๋ณตํ•œ๋‹ค. ์ด๋ฅผ ์œ„ํ•ด `stack`์„ ์ด์šฉํ•˜๊ณ , ์ค‘๋ณต์„ ๋ง‰๊ธฐ ์œ„ํ•ด `defualtdict`๋ฅผ ํ™œ์šฉํ•˜์—ฌ ๋ฐฉ๋ฌธ ์—ฌ๋ถ€๋ฅผ ์ฒดํฌํ•˜์˜€๋‹ค. 

 

์ฝ”๋“œ

from collections import defaultdict


def solution(begin, target, words):
    answer = 0
    stack = [begin]
    visited = defaultdict(bool)

    if target not in words:
        return answer

    while stack:
        cur_word = stack.pop()

        if cur_word == target:
            break

        for next_word in words:
            diff_cnt = 0

            if visited[next_word]:
                continue

            for c, n in zip(cur_word, next_word):
                if c != n:
                    diff_cnt += 1
                if diff_cnt > 1:
                    break
            else:
                visited[next_word] = True
                stack.append(next_word)

        answer += 1

    return answer

 ๋ณ€ํ™˜ ๊ฐ€๋Šฅํ•œ ๋ชจ๋“  ๋‹จ์–ด๋ฅผ stack์— ์ถ”๊ฐ€ํ•˜๋ฉด, ํ•œ๋ฒˆ์˜ ์‹œ๋„๊ฐ€ ๋๋‚œ ๊ฒƒ์ด๋ฏ€๋กœ answer += 1์„ ํ•ด์ค€๋‹ค. stack์˜ ๋‹จ์–ด๊ฐ€ target๊ณผ ๊ฐ™๋‹ค๋ฉด,  ๋” ์ด์ƒ ํƒ์ƒ‰์„ ์ง„ํ–‰ํ•  ํ•„์š”๊ฐ€ ์—†๋‹ค.

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€