127. Word Ladder

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) {

        Queue<String> queue = new LinkedList<>();
        int len = 0;

            int size = queue.size();
            for(int i=0; i< size; i++){
                String s = queue.poll();
                if(s.equals(endWord)) return len;
                for(String n : getNext(s, wordList)){

        return 0;

    private Set<String> getNext(String s, Set<String> wordList){
        char[] chars = s.toCharArray();
        Set<String> res = new HashSet<String>();
        for(int i=0; i< chars.length; i++){
            char c = chars[i];
            for(char x ='a'; x <= 'z'; x++){
                if(c == x) continue;
                chars[i] = x;
                String next = new String(chars);
                chars[i] = c;
        return res;

results matching ""

    No results matching ""