码迷,mamicode.com
首页 > 其他好文 > 详细

127. Word Ladder

时间:2018-06-16 11:51:33      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:note   time   may   hat   lower   must   queue   sam   find   

问题描述:

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.

 

解题思路:

这道题用BFS来解会更快找到答案,因为我们要找的是最短的变化。

我们可以对当前单词的每一个字母进行替换并且去判断新产生的单词是否在wordList里,为了能够快速判断是否在wordList里,我们用一个set来存储wordList里的单词。

用map来存储从beginWord到该word的步数。

用queue来辅助我们进行bfs,提出队首位置的单词,对单词每一个字母进行变换尝试,在变化中记得要检查以下内容:

  1.是否是endWord

  2.是否是wordList里的单词:

    a.若不是,则可以进行下一个尝试

    b.若是,则检查是否在map里出现过,若出现过,则表明我们已经访问过该单词,再次访问会出现环;若没有出现过,则表明这是一个可能的单词,将其压入队中。

在bfs的时候我们要检查是否是endWord,如果是的话就返回map[word]+1。

 

代码:

class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        unordered_set<string> dict(wordList.begin(), wordList.end());
        unordered_map<string, int> m;
        queue<string> q;
        m[beginWord] = 1;
        q.push(beginWord);
        while(!q.empty()){
            string word = q.front();
            q.pop();
            for(int i = 0; i < word.size(); ++i){
                string newWord = word;
                for(char c = a; c <= z; c++){
                    newWord[i] = c;
                    if(dict.count(newWord) && newWord == endWord){
                        return m[word]+1;
                    }
                    if(dict.count(newWord) && !m.count(newWord)){
                        q.push(newWord);
                        m[newWord] = m[word]+1;
                    }
                }
            }
        }
        return 0;
    }
};

 

127. Word Ladder

标签:note   time   may   hat   lower   must   queue   sam   find   

原文地址:https://www.cnblogs.com/yaoyudadudu/p/9189885.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!