Word Ladder
Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
- Return 0 if there is no such transformation sequence.
- All words have the same length.
- All words contain only lowercase alphabetic characters.
- You may assume no duplicates in the word list.
- You may assume beginWord and endWord are non-empty and are not the same.
1 | Example 1: |
Problem Analysis
Like a BFS Level Traversal problem, need to try every possible word of the current Words.
Algorithm Analysis
Find the shortest path, what I could think about is to use a BFS Algorithm. It likes tree structure problems, from the beginning word, I see it as a root node and its child will be all possible words that exist in the word list. So, to search the word in the list more efficiently, I will put all words into a map and its value will be used to record if I have already visited the word. Since if we meet the word that has been visited before in the previous level, which mean the current path might not be the shortest one.
Used a Queue to record all incoming string that need to be processed, and a step counter to record the current step, by level traverse all string, I first check if the end word is equal to the current word, if yes, it will return the current step, if not I will use a function to generate all possible words and check if that word is in the map and has not been visited, put that word into the queue and mark as visited.
Time Complexity Analysis
Time Complexity: (n26)^L
n = number of words in the list
L = length of each word in list
Code Implementation
1 | class Solution { |