반응형
https://programmers.co.kr/learn/courses/30/lessons/43163
코딩테스트 연습 - 단어 변환 | 프로그래머스
두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다. 1. 한 번에 한 개의 알파벳만 바꿀 수 있습니다. 2. words에 있는 단어로만 변환할 수 있습니다. 예를 들어 begin이 hit, target가 cog, words가 [hot,dot,dog,lot,log,cog]라면 hit -> hot -> dot -> dog ->
programmers.co.kr


꽤 예전에 풀었던 문제. 그래서 코드가 효율적인 편은 아니다.
현재 단어에서 '바꿀 수 있는 다음 단어'를 계속 찾아가면서, 더 이상 바꿀 수 없거나 정답과 일치할 때까지 반복한다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def solution(begin, target, words): | |
if target not in set(words): | |
return 0 | |
queue = [begin] | |
total_count = 0 | |
while len(words) != 0: | |
for value in queue: | |
# 바꾸게 될 단어를 저장하는 변수 | |
temp = [] | |
for word in words: | |
count = 0 | |
for idx in range(len(word)): | |
# 원래 단어와 words의 각 단어를 비교해서 | |
# 단어가 다르면 count 증가. | |
if value[idx] != word[idx]: | |
count += 1 | |
if count == 2: | |
# 한 번에 하나만 바꿀 수 있다고 했으니 | |
# 값이 다른 게 두 개 이상이면 더 볼 필요 없다 | |
break | |
# 각 word 단어를 비교한 다음 | |
# 바꿀 수 있는 단어면 temp에 저장하고 | |
# words에서 단어를 삭제한다. | |
if count == 1: | |
temp.append(word) | |
words.remove(word) | |
total_count += 1 | |
if target == "".join(temp): | |
return total_count | |
else: | |
queue = temp | |
return 0 |
반응형
'프로그래밍 > 코딩테스트 문제풀이' 카테고리의 다른 글
[Python] 백준 3055. 탈출 (0) | 2019.12.01 |
---|---|
[Python] 백준 1261. 알고스팟 (0) | 2019.11.30 |
[Python] 프로그래머스. 2020 카카오 recruit - 기둥과 보 설치 (Level 3) (0) | 2019.11.28 |
[Python] 프로그래머스. 단속카메라 (Level 3) (0) | 2019.11.27 |
[Python] 백준 3190. 뱀 (0) | 2019.11.26 |