본문 바로가기

알고리즘

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

DFS

def solution(begin, target, words):
    if target not in words :
        return 0
    
    visited = []
    answer = 0
    dfs_flag = True #답을 찾으면 False, 모든 DFS 종료
    
    def dfs(begin, point):
        visited.append(begin)
        point += 1
        
        #탈출 조건
        cnt = 0
        for i in range(len(begin)):
            if begin[i] != target[i]:
                cnt+=1
        if cnt == 1:
            nonlocal answer
            answer = point
            nonlocal dfs_flag
            dfs_flag = False
            return
         
        #실행문
        for word in words:
            flag = 0
            if word not in visited  and dfs_flag:
                for i in range(len(word)):
                    if begin[i] != word[i]:
                        flag += 1
                if flag == 1 and dfs_flag:
                    dfs(word, point)
    dfs(begin, 0)
    return answer


print(solution("hit","cog",["hot", "dot", "dog", "lot", "log", "cog"]))

아직은 많이 익숙치가 않은것 같다 🥲