S E P H ' S

[Python] 단어 변환 본문

Algorithm/Programmers

[Python] 단어 변환

yoseph0310 2021. 8. 7. 16:19
 

코딩테스트 연습 - 단어 변환

두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다. 1. 한 번에 한 개의 알파벳만 바꿀 수

programmers.co.kr

def solution(begin, target, words):
    answer = len(words)
    depth = -1
    if target not in words:
        return 0
    
    answer = DFS(begin, target, words, depth, answer)
    return answer

def DFS(begin, target, words, depth, answer):
    depth += 1
    nextWord = []
    if begin == target:
        if depth <= answer:
            answer = depth
        return answer
    
    for word in words:
        cnt = 0
        for idx, char in enumerate(word):
            if begin[idx] != char:
                cnt += 1
        
        if cnt == 1:
            nextWord.append(word)
    
    if begin in words:
        words.remove(begin)
    
    for begin in nextWord:
        answer = DFS(begin, target, words, depth, answer)
    
    return answer

'Algorithm > Programmers' 카테고리의 다른 글

[Python] 카펫  (0) 2021.08.08
[Python] 여행 경로  (0) 2021.08.07
[Python] 네트워크  (0) 2021.08.07
[Python] 땅따먹기  (0) 2021.07.31
[Python] 숫자의 표현  (0) 2021.07.31