程序媛詹妮弗
终身学习

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:

  1. Only one letter can be changed at a time.
  2. Each transformed word must exist in the word list. Note that beginWord is not a transformed word.

Note:

  • Return 0 if there is no such transformation sequence.
  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
  • You may assume no duplicates in the word list.
  • You may assume beginWord and endWord are non-empty and are not the same.

Example 1:

Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]

Output: 5

Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.

思路

BFS

 

代码

 1 class Solution {
 2    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
 3     // use dict to check duplicats 
 4     Set<String> dict = new HashSet<>(wordList);
 5     Queue<String> queue = new LinkedList<>();
 6     queue.add(beginWord);
 7     int level = 0;
 8     while(!queue.isEmpty()){
 9         int size = queue.size();
10         for(int i = 0; i < size; i++){
11             String cur = queue.remove();
12             if(cur.equals(endWord)){ return level + 1;}
13             for(int j = 0; j < cur.length(); j++){
14                 // hit -> {'h', 'i', 't'}
15                 char[] charArray = cur.toCharArray();
16                 for(char c = 'a'; c <='z'; c++){
17                     // {'h', 'i', 't'} for'h', try checking 'a','b'...'z' which forms ait, bit...zit
18                     charArray[j] = c;
19                     String temp = new String(charArray);
20                     if(dict.contains(temp)){
21                         queue.add(temp);
22                         // to avoid dead loop, like hit will find hit itself
23                         dict.remove(temp);
24                     }
25                 }
26             }
27         }
28         level++;
29     }
30     return 0;
31  }
32 }

 

posted on 2018-10-21 05:50  程序媛詹妮弗  阅读(144)  评论(0编辑  收藏  举报