DevYoon

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋‹จ์–ด ๋ณ€ํ™˜ (Python) ๋ณธ๋ฌธ

PS/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋‹จ์–ด ๋ณ€ํ™˜ (Python)

gimewn 2022. 4. 19. 16:35

link ๐Ÿ”— https://programmers.co.kr/learn/courses/30/lessons/43163

 

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

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

programmers.co.kr

 

def solution(begin, target, words):
    if target not in words:
        answer = 0
    else:
        def bfs(start, level):
            q = []
            q.append((start, level))
            while q:
                nowwords, level = q.pop(0)
                if nowwords == target:
                    return level
                for word in words:
                    temp = [0]*len(word)
                    for idx in range(len(word)):
                        if nowwords[idx] != word[idx]:
                            temp[idx] = 1
                    if sum(temp) == 1:
                        q.append((word, level+1))

        answer = bfs(begin, 0)

    return answer