[算法分析与设计] leetcode 每周一题: Word Ladder

题目链接:https://leetcode.com/problems/word-ladder/description/

题目 :

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.

For example,

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

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


思路:

一开始我是用图的思想写此题,把每个字典里的字符串作为结点,两个字符串只有一个字母变化才有边,但是后来写不下去了,就看了别人博客,发现可以广度搜索解决。。。

大体上是这样的,首先为了减少每次查询字典的时间(如果每次都遍历vector<sting>,有点浪费时间),需要将字典词列表存储在set中,其次,维护一个map,key是字符串,value是广搜到这个字符串节点的路径长度,接着压入源字符广搜。


注意要点:

1. endWord极有可能是没办法生成的,如果endWord根本就不在字典里,所以需要当newWord == endWord 时就判断合法性,或者一开始就判断

2.存在无限广搜的情况,因为如果有解的话,路径中的节点必然不可能重复,如果压入节点时候,没有查重,就会无限广搜


代码如下:

class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
        map<string, int>pathLen;// 记录每个点的路径耗散
        pathLen[beginWord] = 1;
        int len = beginWord.size(); // 记录字长
        set<string> dict(wordList.begin(), wordList.end());// 字典查询变化后的word是否合法
        queue<string> wordQueue; 
        wordQueue.push(beginWord);
        stringstream ss;

        while(!wordQueue.empty()) {
            string word = wordQueue.front();
            wordQueue.pop();
            for(int i = 0; i < len; i++) {
                string newWord = word;
                for(char j = 'a' ;j <= 'z'; j++) {
                    if(word[i] != j) {
                        newWord[i] = j;
                        if(dict.find(newWord) != dict.end() && newWord == endWord) {
                            return pathLen[word] + 1;

                        }
                        if(dict.find(newWord) != dict.end() && pathLen.find(newWord) == pathLen.end()) {
                            pathLen[newWord] = pathLen[word] + 1;
                            wordQueue.push(newWord);
                        }
                    }
                }
            }
            
        }
        return 0;
    }
};


猜你喜欢

转载自blog.csdn.net/liangtjsky/article/details/78602712