【LeetCode】127. Word Ladder

Bertha 。 2022-03-31 10:50 267阅读 0赞

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

  1. struct Node
  2. {
  3. string word;
  4. int len;
  5. Node(string w, int l): word(w), len(l) {}
  6. };
  7. class Solution {
  8. public:
  9. int ladderLength(string beginWord, string endWord, unordered_set<string>& wordDict) {
  10. queue<Node*> q;
  11. unordered_map<string, bool> m;
  12. Node* beginNode = new Node(beginWord, 1);
  13. q.push(beginNode);
  14. m[beginWord] = true;
  15. while(!q.empty())
  16. {
  17. Node* frontNode = q.front();
  18. q.pop();
  19. string frontWord = frontNode->word;
  20. //neighbor search
  21. for(int i = 0; i < frontWord.size(); i ++)
  22. {
  23. for(char c = 'a'; c <= 'z'; c ++)
  24. {
  25. if(c == frontWord[i])
  26. continue;
  27. string frontWordCp = frontWord;
  28. frontWordCp[i] = c;
  29. //end
  30. if(frontWordCp == endWord)
  31. return frontNode->len+1;
  32. if(wordDict.find(frontWordCp) != wordDict.end() && m[frontWordCp] == false)
  33. {
  34. Node* neighborNode = new Node(frontWordCp, frontNode->len+1);
  35. q.push(neighborNode);
  36. m[frontWordCp] = true;
  37. }
  38. }
  39. }
  40. }
  41. return 0;
  42. }
  43. };

181128122607086.jpg

发表评论

表情:
评论列表 (有 0 条评论,267人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Word Ladder--LeetCode

    这道题看似一个关于字符串操作的题目,其实要解决这个问题得用图的方法。我们先给题目进行图的映射,顶点则是每个字符串,然后两个字符串如果相差一个字符则我们进行连边。接下来看看这个方