Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWordto 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.
For example,
Given:
beginWord =
endWord =
wordList =
beginWord =
"hit"
endWord =
"cog"
wordList =
["hot","dot","dog","lot","log","cog"]
As one shortest transformation is
return its length
"hit" -> "hot" -> "dot" -> "dog" -> "cog"
,return its length
5
.
Note:
- 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.
UPDATE (2017/1/20):
The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
The wordList parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
Solution:
Use BFS.
In each level, we try to find all one edit distance word from the current word.
For each one edit distance word, we check if it is the endWord.
If it is the endWord, we return the level.
If it is not, we check if it is in the word list. If so, we add it in queue.
Code:
public class Solution { public int ladderLength(String beginWord, String endWord, List<String> wordList) { if (beginWord.equals(endWord)) { return 1; } HashSet<String> dict = new HashSet<>(); for (String word : wordList) { dict.add(word); } if (!dict.contains(endWord)) { return 0; } Queue<String> queue = new LinkedList<>(); queue.offer(beginWord); dict.remove(beginWord); int level = 2; while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { String word = queue.poll(); for (int j = 0; j < word.length(); j++) { char[] chars = word.toCharArray(); for (char c = 'a'; c <= 'z'; c++) { chars[j] = c; String neighbor = new String(chars); if (neighbor.equals(endWord)) { return level; } if (dict.remove(neighbor)) { queue.offer(neighbor); } } } } level++; } return 0; } }