120. Word Ladde——单词接龙(BFS分层遍历)

Description

【120. Word Ladde——单词接龙(BFS分层遍历)】
给出两个单词(start和end)和一个字典,找到从start到end的最短转换序列
比如:

  1. 每次只能改变一个字母。
  2. 变换过程中的中间单词必须在字典中出现。
注意事项
  • 如果没有转换序列则返回0。
  • 所有单词具有相同的长度。
  • 所有单词都只包含小写字母。
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the dictionary
Notice
  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
Example Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]

As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
TagsLinkedInBreadth First Search Solution 思路:
1. 使用BFS分层搜索每层可能的下一个单词,并把层号加一。
2. 遍历下个单词的所有可能,如果已出现过这个可能则直接跳过,将没出现过的记录到Set和Queue中。
3. 如果下个单词为end,则返回层数。如果知道队列为空都没找到,则返回0。
public class Solution { /* * @param start: a string * @param end: a string * @param dict: a set of string * @return: An integer */ public int ladderLength(String start, String end, Set dict) { // write your code here if (dict == null) { return 0; } if (start.equals(end)) { return 1; }//为了能搜出这个结果,end需在字典中 dict.add(start); dict.add(end); //BFS搜索每层可能的结果,并比较知否找到end Queue queue = new LinkedList<>(); HashSet set = new HashSet<>(); queue.offer(start); set.add(start); int length = 1; while (!queue.isEmpty()) { length++; //遍历每层可能的结果前计数值加一 int size = queue.size(); for (int i = 0; i < size; i++) { String word = queue.poll(); //遍历下个单词的所有可能,如果已出现过这个可能则直接跳过,将没出现过的记录下来 for (String nextWord : getNextWords(word, dict)) { if (set.contains(nextWord)) { continue; } if (nextWord.equals(end)) { return length; } set.add(nextWord); queue.offer(nextWord); } } } return 0; }//找到所有可能的结果,看看是不是在字典中有出现,如果出现就记录下来 // get connections with given word. // for example, given word = 'hot', dict = {'hot', 'hit', 'hog'} // it will return ['hit', 'hog'] private ArrayList getNextWords(String word, Set dict) { ArrayList nextWords = new ArrayList<>(); for (char c = 'a'; c < 'z'; c++) { for (int i = 0; i < word.length(); i++) { if (c == word.charAt(i)) { continue; } String nextWord = replace(word, i, c); if (dict.contains(nextWord)) { nextWords.add(nextWord); } } } return nextWords; }// replace character of a string at given index to a given character // return a new string private String replace(String s, int index, char c) { char[] chars = s.toCharArray(); chars[index] = c; return new String(chars); } }


    推荐阅读