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.

Solution 1: Time Limit Exceeded

public class Solution {
    public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
        Queue<String> q = new LinkedList<>();
        q.offer(beginWord);
        int len = beginWord.equals(endWord) ? 0 : 1;
        while(!q.isEmpty()){
            Queue<String> tmp = new LinkedList<>();
            while(!q.isEmpty()){
                String s1 = q.poll();
                if(isAdj(s1, endWord)) return len + 1;
                Set<String> set = new HashSet<>(wordList);
                for(String s2 : wordList){
                    if(isAdj(s1, s2)) {
                        tmp.add(s2);
                        set.remove(s2);
                    }
                }
                wordList = set;
            }
            len++;
            q = tmp;
        }
        return 0;
    }
    public boolean isAdj(String s1, String s2){
        int chance = 1;
        for(int i=0; i<s1.length(); i++){
            if(s1.charAt(i)!=s2.charAt(i)) chance--;
            if(chance<0) return false;
        }
        return true;
    }
}
comments powered by Disqus