반응형

https://programmers.co.kr/learn/courses/30/lessons/43163

 

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

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

programmers.co.kr

 

해결 방법 : BFS

  • 단어 개수가 많지 않기 때문에 완전 탐색 가능.
    • target word로의 최소 변환 횟수를 구하는 것이기 때문에 BFS를 사용하면 더 효율적이다.
      • DFS는 모든 경우를 탐색 → 최솟값 반환
      • BFS는 target word가 최소로 나오면 해당 위치 count가 최솟값

 

from collections import deque

def solution(begin, target, words):
    path = []
    Q = deque([(begin, 0)])
    while Q:
        cur_word, count = Q.popleft()
        if cur_word == target: return count
        
        for word in words: # 단어가 하나만 다르고, 이미 거쳐온 단어가 아닐 시, 탐색
            if len([1 for i, j in zip(cur_word, word) if i == j]) == len(word) - 1 and word not in path:
                Q.append((word, count + 1))
                path.append(word)
        
    return 0
반응형

'IT study > 알고리즘 문제 풀이' 카테고리의 다른 글

프로그래머스 : N으로 표현  (0) 2021.06.30
프로그래머스 : 순위  (0) 2021.06.29
프로그래머스 : 더 맵게  (0) 2021.06.28
백준 15486 : 퇴사 2  (0) 2021.06.24
백준 1010 : 다리 놓기  (0) 2021.06.24

+ Recent posts