-
[Python] 단어 변환Algorithm/프로그래머스 2022. 10. 20. 20:13
1. 문제 📚
2. 입출력 예 📋
3. 알고리즘 ✅
1. 한글자만 다른 단어인지 체크
2. 한번도 방문한 적 없는 단어인지 체크 -> visited에 없다면 한번도 방문한 적 없는 단어
3. 파생되어온 word에 +1 해주기
4. 소스코드 💻
from collections import deque # 한글자 체크 def is_valid(begin, target): count = len(begin) for i in range(count): if begin[i] == target[i]: count -= 1 return count == 1 def solution(begin, target, words): def bfs(word): visited = {word: 0} queue = deque([]) queue.append(word) while queue: word = queue.popleft() if word == target: break for value in words: # visited안에 없다면 한번도 방문한적 없던 단어 if is_valid(value, word) and value not in visited: visited[value] = visited[word] + 1 queue.append(value) return visited return bfs(begin).get(target, 0) solution('hit', 'cog', ["hot", "dot", "dog", "lot", "log", "cog"])
'Algorithm > 프로그래머스' 카테고리의 다른 글
[Java] 카펫 (0) 2023.04.04 [Python] 주차 요금 계산 (0) 2022.11.04 [Python] 입국심사 (0) 2021.06.03 [Python] 로또의 최고 순위와 최저 순위 (0) 2021.05.05 [Python] 폰켓몬 (0) 2021.05.03