코딩테스트 고득점 Kit - 깊이/너비 우선 탐색 3 (Level 3)

 

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


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from collections import deque

def solution(begin, target, words):
    dist  = {begin: 0}
    queue = deque([begin])
    words = [begin] + words
    adjs  = {v1: [v for v in words if sum([x!=y for x,y in zip(v1, v)]) == 1] for v1 in words}

    while queue:
        current = queue.popleft()
        for next_word in adjs[current]:
            if next_word not in dist:
                dist[next_word] = dist[current] + 1
                queue.append(next_word)
    return dist.get(target, 0)

Complexity

$O(|V||E|)$

  • $V$ = vertices
  • $E$ = edges