Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
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:
Java AC
public class Solution { public int ladderLength(String start, String end,HashSet<String> dict) { if (dict == null || dict.isEmpty()) { return 0; } Queue<Node> strQueue = new LinkedList<Node>(); HashSet<String> visitedSet = new HashSet<String>(); strQueue.add(new Node(start, 1)); visitedSet.add(start); int wordLen = start.length(); while (!strQueue.isEmpty()) { Node node = strQueue.peek(); strQueue.poll(); for (int i = 0; i < wordLen; i++) { StringBuffer sb = new StringBuffer(node.word); for (char j = 'a'; j <= 'z'; j++) { sb.setCharAt(i, j); String tempWord = sb.toString(); if (tempWord.equals(end)) { return node.len+1; }else { if (dict.contains(tempWord) && !visitedSet.contains(tempWord)) { strQueue.add(new Node(tempWord, node.len+1)); visitedSet.add(tempWord); } } } } } return 0; } private static class Node{ String word; int len; public Node(String word, int len) { super(); this.word = word; this.len = len; } } }