leetcode-WordLadder

题目:
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.

由于只需要求最短的距离,所以直接BFS就行了。这题OJ的数据卡得比较严,裸BFS会TLE。没有必要写双向的BFS,注意下剪枝就可以了。直接放代码。
code:

import java.util.*;

public class WordLadder {
    public int ladderLength(String beginWord, String endWord, Set wordList) {
        HashMap map = new HashMap();
        LinkedList queue = new LinkedList();
        
        queue.offer(beginWord);
        map.put(beginWord, 1);
        boolean flag = false;
        while(!queue.isEmpty()){
            String curr = queue.poll();
            for(String next : getNextWords(curr, wordList)){
                if(next.equals(endWord)){
                    flag = true;
                    map.put(next, map.get(curr) + 1);
                    System.out.println(next + " " + map.get(next));
                    return map.get(next);
                }
                if(wordList.contains(next)){
                    if(!map.containsKey(next)){
                        map.put(next, map.get(curr) + 1);
                        System.out.println(next + " " + map.get(next));
                        queue.offer(next);
                    }
                }
            }
        }
        if(flag) return map.get(endWord);
        else return 0;
    }
    
    public List getNextWords(String word, Set wordList){
        List nextWords = new ArrayList();
        for(int i = 0; i < word.length(); i++){
            for(char c = 'a'; c <= 'z'; c++){
                if(c == word.charAt(i)) continue;
                char[] arr = word.toCharArray();
                arr[i] = c;
                String next = new String(arr);
                if(wordList.contains(next)) nextWords.add(next);
            }
        }
        return nextWords;
    }
    
    public static void main(String[] args){
        WordLadder WL = new WordLadder();
        Set wordList = new HashSet();
        wordList.add("a");
        wordList.add("b");
        wordList.add("c");
        String beginWord = "a";
        String endWord = "c";
        int result = WL.ladderLength(beginWord, endWord, wordList);
        System.out.println(result);
    }
}

你可能感兴趣的:(backtracking)