zoukankan      html  css  js  c++  java
  • 【LeetCode】127. Word Ladder

    Word Ladder

    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

    For 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.

    Note:

      • Return 0 if there is no such transformation sequence.
      • All words have the same length.
      • All words contain only lowercase alphabetic characters.

    最短搜索路径,所以是广度优先搜索(BFS)。

    有几个问题需要注意:

    1、怎样判断是否为邻居节点?

    按照定义,存在一个字母差异的单词为邻居,因此采用逐位替换字母并查找字典的方法寻找邻居。

    (逐个比对字典里单词也可以做,但是在这题的情况下,时间复杂度会变高,容易TLE)

    2、怎样记录路径长度?

    对队列中的每个单词记录路径长度。从start进入队列记作1.

    长度为i的字母的邻居,如果没有访问过,则路径长度为i+1

    struct Node
    {
        string word;
        int len;
        
        Node(string w, int l): word(w), len(l) {}
    };
    
    class Solution {
    public:
        int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
            queue<Node*> q;
            unordered_map<string, bool> m;
            Node* beginNode = new Node(beginWord, 1);
            q.push(beginNode);
            m[beginWord] = true;
            while(!q.empty())
            {
                Node* frontNode = q.front();
                q.pop();
                string frontWord = frontNode->word;
                //neighbor search
                for(int i = 0; i < frontWord.size(); i ++)
                {
                    for(char c = 'a'; c <= 'z'; c ++)
                    {
                        if(c == frontWord[i])
                            continue;
                            
                        string frontWordCp = frontWord;
                        frontWordCp[i] = c;
                        //end
                        if(frontWordCp == endWord)
                            return frontNode->len+1;
                        if(wordDict.find(frontWordCp) != wordDict.end() && m[frontWordCp] == false)
                        {
                            Node* neighborNode = new Node(frontWordCp, frontNode->len+1);
                            q.push(neighborNode);
                            m[frontWordCp] = true;
                        }
                    }
                }
            }
            return 0;
        }
    };

  • 相关阅读:
    vs2019编译错误:Exception Processing Message 0xc0000005 Parameters...
    error LNK2001
    Debug Assertion Failed
    对路径“………………”的访问被拒绝
    c语言打开文件为什么总是以二进制方式打开
    关于typedef的用法总结
    xml学习第一天
    关于VS2017编译成功系统找不到指定文件.exe的问题
    引入的外部js文件在html文件在浏览器中乱码显示
    结对作业(四则运算)
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4125695.html
Copyright © 2011-2022 走看看