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;
        }
    };

  • 相关阅读:
    C#判断闰年
    C#计算时间,107653秒是几天几小时几分钟几秒?
    两个值交换,不使用第三个中间变量做缓存。实现方法
    element UI dialog 固定高度 且关闭时清空数据
    JS
    PHP
    element UI 上传文件成功后
    windows环境安装vue-cli及webpack并创建vueJs项目
    PHP
    mysql点滴记录 三 (基础操作)
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4125695.html
Copyright © 2011-2022 走看看