본문 바로가기
코딩테스트 파이썬/파이썬 프로그래머스 3단계

단어 변환

by 세용용용용 2023. 10. 25.

 

나의 코드

from collections import deque
def solution(begin, target, words):
    answer = 0
    queue = deque()
    queue.append((begin, 0))

    visit = [0]*len(words)
    print(visit)

    while queue:
        string, count = queue.popleft()

        # 타겟 단어와 같으면 break
        if string == target:
            answer = count
            break
       
        for i in range(len(words)):
            # 단어 비일치 여부 카운트
            same_count = 0
            # 방문 하지 않은 단어일떄
            if visit[i] == 0:
                for j in range(len(words[i])):
                    if words[i][j] != string[j]:
                        same_count+=1
           
            # 하나의 단어만 다를경우
            if same_count == 1:
                queue.append((words[i], count+1))
                visit[i] = 1
    #print(answer)
    return answer
solution('hit','cog',["hot", "dot", "dog", "lot", "log", "cog"])