127. Word Ladder(js)

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:

  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.

Example 2:

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

Output: 0

Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
题意:单词接龙,给定初始单词和结束单词。每次只改变单词一个字符并且改变后的单词必须存在于单词列表(wordList)中,返回接龙数量最小的值
代码如下:
/**
 * @param {string} beginWord
 * @param {string} endWord
 * @param {string[]} wordList
 * @return {number}
 */
var ladderLength = function(beginWord, endWord, wordList) {
    let len=1;
    let queue=[beginWord];
    let dict=new Set(wordList);
    let seen=new Set(queue);
    while(queue.length){
        const next=[];
        for(let v of queue){
            if(v===endWord){
                return len;
            }
            const arr=v.split('');
//             暴力替换,对当前单词的所有字符进行替换
            for(let i=0;i<arr.length;i++){
                for(let c=0;c<26;c++){
                    arr[i]=String.fromCharCode(97+c);
                    let nv=arr.join('');
//                     尚未选择的,并且存在于dict列表中的单词
                    if(!seen.has(nv) && dict.has(nv)){
                        next.push(nv);
                        seen.add(nv);
                    }
                    arr[i]=v[i];
                }
            }
        }
        queue=next;
        len++;
    }
    return 0;
    
};

 

posted @ 2019-05-22 23:29  mingL  阅读(198)  评论(0编辑  收藏  举报