Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Tags
more
Archives
Today
Total
관리 메뉴

No Limitation

[DFS] 단어 변환 - 프로그래머스 본문

프로그래밍

[DFS] 단어 변환 - 프로그래머스

yesungcho 2022. 1. 30. 21:09

https://programmers.co.kr/learn/courses/30/lessons/43163?language=python3 

 

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

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

programmers.co.kr

 

Fact Finding


  • DFS 문제를 통해 최소 변환 횟수를 찾기

Algorithm Flow


  • recursion을 통한 DFS 구현 후 가장 최소의 경우를 final_result에 저장

여기서 주의해야 할 부분이 바로 global 변수의 활용이다!!

 

구현 코드

# 반례
# hit
# cog
# cog cot dot dog dut
#global a
#a = 0
def check(begin, target) : ## 한 개의 알파벳만 바꾸기 위한 check 함수
    check_count = 0
    for i in range(len(target)) : 
        if begin[i] != target[i] : 
            check_count += 1
    if check_count == 1 : 
        return True
    return False

def problem(now, targt, words, final_result=100000000, result = 0): 
    global a
    a = 0
    if now == targt : ## Base case
        #global a
        a = 1
        return result
    for i in words : 
        if i != now : 
            if check(now, i) : ## 전환 가능한 경우
                index = words.index(i)
                del words[index] ## 해당 단어 제외
                result = problem(i, targt,words) + 1 ## Depth First Search
                final_result = min(result, final_result) ## 가장 최저 경로를 저장
                words.insert(index, i) ## recursion이 끝난 뒤로 다시 추가
    if a == 0 : 
        return 0
    return final_result
    

def solution(begin, target, words):
    answer = 0
    if target in words : 
        answer = problem(begin, target, words)
    return answer