[프로그래머스] 43163번 단어 변환

Effy_ee·2024년 8월 20일
0

코딩테스트

목록 보기
110/118

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

from collections import deque

#두 단어가 한 자리만 다른지 체크
def check(word1,word2):
    count=0
    for i in range(len(word1)):
        if word1[i]!=word2[i]:
            count+=1
    if count==1:
        return True
    return False


def bfs(words,visited,begin,target):
    q=deque()
    q.append([begin,0])

    while q:
        now,count=q.popleft()
        #목표 달성 시 답 반환
        if now==target:
            return count
        #모든 단어의 리스트를 순회하면서
        for i in range(len(words)):
        # 1. 사용된 적이 없는 단어이고
            if not visited[i]:
          	#2. 한 글자만 다르면 모두 다 큐에 넣기
                if check(now,words[i]):
                    visited[i]=True
                    q.append((words[i],count+1))


def solution(begin, target, words):
	#target이 단어 리스트에 없는 경우
    if target not in words:
        return 0
    visited=[False]*len(words)
    answer=bfs(words,visited,begin,target)
    return answer

0개의 댓글