https://programmers.co.kr/learn/courses/30/lessons/43163
코딩테스트 연습 - 단어 변환
두 개의 단어 begin, target과 단어의 집합 words가 있습니다. 아래와 같은 규칙을 이용하여 begin에서 target으로 변환하는 가장 짧은 변환 과정을 찾으려고 합니다. 1. 한 번에 한 개의 알파벳만 바꿀 수
programmers.co.kr
Solution
from collections import deque
def solution(begin, target, words):
answer = 0
q = deque()
q.append([begin,0])
visit = [False]*len(words)
while q:
word, n = q.popleft()
if word == target:
return n
for idx, w in enumerate(words):
cnt = 0
if visit[idx] == False:
for j in range(len(word)):
if word[j] != w[j]:
cnt += 1
if cnt==1: # 한글자만 다른 경우, q.append()
q.append([w,n+1]) # [변환 단어, 변환 횟수]
visit[idx] = True
return 0
BFS로 해결!
'Programming > DFSBFS' 카테고리의 다른 글
Programmers / 단어 변환 (0) | 2022.04.29 |
---|---|
Baekjoon / BFS / 음식물피하기 (0) | 2022.03.25 |
Baekjoon / BFS / 연결 요소의 개수 (0) | 2022.02.13 |
Baekjoon / DFS / 유기농 배추 (0) | 2022.02.13 |
Baekjoon / BFS / 미로탐색 (0) | 2022.02.11 |