본문 바로가기
스터디/알고리즘

단어변환

by 세졍 2024. 2. 25.

 

bfs

1. begin이 target 이되는 최소 단계수이므로 bfs

 

def bfs(begin, target, words):
    queue = [(begin, 0)] // 현재 단어와 , 단계를 큐에담기
    while queue:
        now, step = queue.pop(0)
        if now == target:
            return step
        for word in words:
            cnt = 0
            for i in range(len(now)):
                if word[i] == now[i]:
                    cnt += 1
            if cnt == len(now)-1 : // 최소 알파벳 하나만 변해야 하므로 
                queue.append([word,step+1])


def solution(begin, target, words):
    if target not in words:    // target 단어가 words에 없으면 0반환
        return 0
    return bfs(begin, target, words)
    
    
    
begin = "hit"
target = "cog"
words = ["hot", "dot", "dog", "lot", "log", "cog"]
print(solution(begin,target,words))

'스터디 > 알고리즘' 카테고리의 다른 글

타겟넘버  (1) 2024.02.28
게임 맵 최단거리  (0) 2024.02.28
바이러스  (0) 2024.02.23
네트워크  (0) 2024.02.23
모음사전  (0) 2024.02.23