from collections import deque

def find_word_path(begin, target, words):
    if target not in words:
        return 0

    q = deque()
    q.append((begin, 0))
    visited = set()
    visited.add(begin)

    while q:
        word, cnt = q.popleft()

        if word == target:
            return cnt

        for w in words:
            if w not in visited:
                diff = 0
                for a, b in zip(word, w):
                    if a != b:
                        diff += 1
                if diff == 1:
                    visited.add(w)
                    q.append((w, cnt + 1))

    return 0


begin = "hit"
target = "cog"
words = ["hot", "dot", "dog", "lot", "log", "cog"]

print(find_word_path(begin, target, words))

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: