L3 : 단어 변환 Python

jhyunn·2023년 1월 19일
0

Programmers

목록 보기
43/69

L3 : 단어 변환 Python

https://school.programmers.co.kr/learn/courses/30/lessons/43163

from collections import deque

def solution(begin, target, words):
    visited = [0]*len(words)
    dq = deque()
    dq.append([begin, 0])
    
    while dq:
        cur_word, cnt = dq.popleft()
        
        if cur_word == target:
            return cnt
            
        for i, word in enumerate(words):
            if len(word) == len(cur_word):
                compare = 0
                for w, c in zip(word, cur_word):
                    if w != c:
                        compare += 1
                    if compare > 1:
                        break
                        
                if visited[i] == 0 and compare == 1:
                    visited[i] = 1
                    dq.append([word, cnt+1])
    return 0

#BFS

profile
https://github.com/Sungjeonghyun

0개의 댓글