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 intermediate word must exist in the word list
For example,

Given:
beginWord = “hit”
endWord = “cog”
wordList = [“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 {
public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
//BFS to solve the problem
int count = 1;
Set<String> reached = new HashSet<String>();
while (!reached.contains(endWord)) {
for (String word : reached) {
for (int i = 0; i < word.length(); i  ) {
char[] chars = word.toCharArray();
for (char c = 'a'; c <= 'z'; c  ) {
chars[i] = c;
String newWord = String.valueOf(chars);
if (wordList.contains(newWord)) {
wordList.remove(newWord);
}
}
}
}
count  ;
if (toAdd.size() == 0) return 0;
}
return count;
}
}``````

``````public class Solution {
public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
int count = 1;
Set<String> beginSet = new HashSet<String>();
Set<String> endSet = new HashSet<String>();
Set<String> visited = new HashSet<String>();
while (!beginSet.isEmpty() && !endSet.isEmpty()) {
if (beginSet.size() > endSet.size()) {
Set<String> temp = beginSet;
beginSet = endSet;
endSet = temp;
}
for (String word : beginSet) {
for (int i = 0; i < word.length(); i  ) {
char[] chars = word.toCharArray();
for (char c = 'a'; c <= 'z'; c  ) {
chars[i] = c;
String newWord = String.valueOf(chars);
if (endSet.contains(newWord)) return count   1;
if (!visited.contains(newWord) && wordList.contains(newWord)) {