← 返回 snapchat 的题目列表Word Ladder Reachability
类型:qbank
Given a start word, target word, and dictionary, return whether the target can be reached by changing one letter at a time, rather than returning the shortest path length.
Requirements
Implement a reachability variant of Word Ladder.
Input shape:
def can_transform(begin_word: str, end_word: str, word_list: list[str]) -> bool:
...
Rules:
Each step changes exactly one character.
Every intermediate word must appear in the dictionary.
All words have the same length.
Return True if any valid transformation exists; otherwise return False.
Run test cases and handle typo-level bugs carefully.
Example:
begin = "hit"
end = "cog"
words = ["hot", "dot", "dog", "lot", "log", "cog"]
answer = True
Notes
This is a graph reachability problem. Each word is a node; an edge exists between words that differ by one character. BFS is the simplest answer because it avoids recursion depth and can be upgraded to shortest path if the interviewer asks.
Precompute wildcard buckets such as h*t -> [hot, hit] to avoid comparing every pair of words. Then each BFS expansion generates patterns for the current word and visits all words in matching buckets.
Complexity with wildcard buckets is roughly O(n * L^2) or O(n * L) depending on implementation details and string slicing costs, where n is dictionary size and L is word length. Space is O(n * L) for buckets.
Preparation
Implement the boolean version first, then modify it to return shortest length.
Practice bidirectional BFS as a follow-up.
Add tests where end_word is missing, begin_word is not in the dictionary, and no path exists.