tech.junha.kr

단어변환: DFS, BFS 풀이

문제 설명

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

  1. 한 번에 한 개의 알파벳만 바꿀 수 있습니다. 2. words에 있는 단어로만 변환할 수 있습니다.

예를 들어 begin이 "hit", target가 "cog", words가 ["hot","dot","dog","lot","log","cog"]라면 "hit" -> "hot" -> "dot" -> "dog" -> "cog"와 같이 4단계를 거쳐 변환할 수 있습니다.

두 개의 단어 begin, target과 단어의 집합 words가 매개변수로 주어질 때, 최소 몇 단계의 과정을 거쳐 begin을 target으로 변환할 수 있는지 return 하도록 solution 함수를 작성해주세요.

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

    def dfs(begin, words, depth,answer):
        depth += 1
        nextWords = []
        if begin == target:
            if depth <= answer:
                answer = depth
            return answer

        for word in words:
            count = 0
            for index, char in enumerate(word):
                if begin[index] != char:
                    count += 1
            if count == 1:
                nextWords.append(word)

        newSearchWords = words[:]
        if begin in newSearchWords:
            newSearchWords.remove(begin)

        for begin in nextWords:
            answer = dfs(begin, newSearchWords, depth,answer)

        return answer

    answer = dfs(begin, words, depth,answer)

    return answer

문제의 핵심:

프로세스는 문제의 최적해를 곧바로 찾는 방식이 아니라,

최적의 해를 구해가는 경우의 수를 구하고, 계속 최적해를 교환해가는 방식이다.