[프로그래머스] 단어 변환 - 파이썬/BFS

JinUk Lee·2023년 3월 2일
0

프로그래머스

목록 보기
21/47

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

from collections import deque

def trans(begin,after):
    count = 0
    for i in range(len(begin)):
        if begin[i]==after[i]:
            count+=1

    if count == len(begin)-1:
        return True
    else:
        return False

def solution(begin, target, words):

    if target not in words:
        return 0

    q = deque([(begin,0)])
    cnt = 0
    while q:
        now,cnt = q.popleft()
        if now == target:
            return cnt

        for i in words:
            if trans(now,i):
                q.append((i,cnt+1))

    answer = 0

    return answer

한개의 알파벳만 바꿔서 words 내부의 단어로 변환 가능한지 여부를 판단해주는 trans 함수를 작성했고

해당 조건을 만족하는 것을 기준으로 BFS를 사용했다.

profile
개발자 지망생

0개의 댓글