Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Created November 12, 2017 15:52
Show Gist options
  • Select an option

  • Save shailrshah/d5268b50a13edb36b94bd725510813c7 to your computer and use it in GitHub Desktop.

Select an option

Save shailrshah/d5268b50a13edb36b94bd725510813c7 to your computer and use it in GitHub Desktop.
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.
public static int ladderLength(String beginWord, String endWord, List<String> wordList) {
int count = 1;
if(beginWord.equals(endWord))
return count;
Queue<String> queue = new LinkedList<>();
Set<String> set = new HashSet<String>(wordList); // contains() is O(1). For ArrayList it's O(n)
queue.add(beginWord);
set.remove(beginWord);
while(queue.size() > 0) {
count++;
int size = queue.size();
for(int i = 0; i < size; i++) { // to keep a track of depth
String polled = queue.poll();
for(int j = 0; j < polled.length(); j++){ // to iterate each character
char[] element = polled.toCharArray();
for(char k = 'a'; k <= 'z'; k++) { // to try all possibilities
element[j] = k;
String word = new String(element);
if(set.contains(word) && word.equals(endWord))
return count;
if(set.remove(word))
queue.add(word);
}
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment