leetcode--Word Ladder
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
- Only one letter can be changed at a time
- Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "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
public class Solution { /** * This is a typical bfs problem. * @param start * @param end * @param dict * @return */ public int ladderLength(String start, String end, Set<String> dict) { if(dict.size() == 0) return 0; if(start.equals(end)) return 1; Queue<String> iteratedQueue = new LinkedList<String>(); Queue<Integer> depth = new LinkedList<Integer>(); iteratedQueue.add(start); depth.add(1); while(iteratedQueue.peek() != null) { String currentWord = iteratedQueue.poll(); int currentDepth = depth.poll(); for(int i = 0; i < currentWord.length(); ++i){ char[] carray = currentWord.toCharArray(); for(char c = 'a'; c <= 'z'; ++c){ carray[i] = c; String possibleWord = new String(carray); if(possibleWord.equals(end)) return currentDepth + 1; if(dict.contains(possibleWord)) { iteratedQueue.add(possibleWord); depth.add(currentDepth + 1); dict.remove(possibleWord); } } } } return 0; } }