알고리즘 스터디 0308

looggi·2023년 3월 11일
0

algorithm

목록 보기
1/2
post-thumbnail

➡️ 단어 변환

from collections import deque

def solution(begin, target, words):
    if target not in words:                                   
        return 0
    
    queue=deque()   
    visited = []
    queue.appendleft([begin,0])                               
    while queue:                                                                
        node,depth = queue.pop()
        if node == target:
            answer = depth
            break
        if node not in visited:                                                 
            visited.append(node)               
            for word in words:
                result = list(filter(lambda x: x[0]!=x[1], zip(node,word)))     
                if len(result) == 1:                                            
                    queue.append([word,depth+1])
    return answer

타겟 단어가 리스트에 없으면 목적지에 도달할 수 없으므로 0을 바로 리턴한다 - 이부분은 없어도 됨
다른 부분은 동일하고 result구하는 부분이 달랐는데
node, word 모두 스트링이므로 iterable하다 ⭐⭐⭐
그래서 zip을 사용해서 각 글자들을 묶은 튜플을 만들어줄 수 있어서
튜플의 각 요소가 다른 걸 체크해줄 수 있고 다른 글자가 있다면 리스트에 담아서
그 다음 조건문에서 result의 길이가 하나, 즉 다른 글자가 하나만 있을 때 큐에 해당 글자를 붙여준다

profile
looooggi

0개의 댓글