leetcode 126. Word Ladder II

ゝ一世哀愁。 2022-08-21 02:19 233阅读 0赞

Given two words (beginWord and endWord), and a dictionary’s word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:

  1. Only one letter can be changed at a time
  2. Each intermediate word must exist in the word list

For example,

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

Return

  1. [
  2. ["hit","hot","dot","dog","cog"],
  3. ["hit","hot","lot","log","cog"]
  4. ]

Note:

  • All words have the same length.
  • All words contain only lowercase alphabetic characters.
  1. class Solution {
  2. vector<vector<string>>re;
  3. int minlen;
  4. void do_once(string endWord, vector<pair<vector<string>, map<char, vector<string>>> >&candi)
  5. {
  6. vector<pair<vector<string>, map<char, vector<string>>> >newcandi;
  7. for (int i = 0; i < candi.size(); i++)
  8. {
  9. if (candi[i].first.size() + 2 <= minlen)
  10. {
  11. string str = candi[i].first[candi[i].first.size()-1];
  12. for (map<char, vector<string>>::iterator it1 =
  13. candi[i].second.begin(); it1 != candi[i].second.end(); it1++)
  14. {
  15. for (int j = 0; j < it1->second.size(); j++)
  16. {
  17. if (string(it1->second[j].begin() + 1, it1->second[j].end()) == string(str.begin() + 1, str.end()))
  18. {
  19. int kk = 0;
  20. for (int jj = 0; jj < it1->second[j].length(); jj++)
  21. if (endWord[jj] != it1->second[j][jj])
  22. kk++;
  23. if (kk == 1)
  24. {
  25. if (candi[i].first.size() + 2 < minlen)
  26. {
  27. minlen = candi[i].first.size() + 2;
  28. re.clear();
  29. vector<string>aa = candi[i].first;
  30. aa.push_back(it1->second[j]);
  31. aa.push_back(endWord);
  32. re.push_back(aa);
  33. }
  34. else if (candi[i].first.size() + 2 == minlen)
  35. {
  36. vector<string>aa = candi[i].first;
  37. aa.push_back(it1->second[j]);
  38. aa.push_back(endWord);
  39. re.push_back(aa);
  40. }
  41. }
  42. else if (candi[i].first.size() + kk + 1 <= minlen)
  43. {
  44. vector<string>aa = candi[i].first;
  45. aa.push_back(it1->second[j]);
  46. map<char, vector<string>>cc = candi[i].second;
  47. cc[it1->first].erase(find(cc[it1->first].begin(),
  48. cc[it1->first].end(), it1->second[j]));
  49. newcandi.push_back(pair < vector<string>,
  50. map<char, vector<string>> > (aa, cc));
  51. }
  52. }
  53. }
  54. }
  55. for (int j = 1; j < endWord.length(); j++)
  56. {
  57. string newstr = str;
  58. newstr .erase(j,1);
  59. for (int h =0;h< candi[i].second[newstr[0]].size();h++)
  60. {
  61. string ss = candi[i].second[newstr[0]][h];
  62. ss.erase(j,1);
  63. if (newstr == ss)
  64. {
  65. int kk = 0;
  66. for (int jj = 0; jj < candi[i].second[newstr[0]][h].length(); jj++)
  67. if (endWord[jj] != candi[i].second[newstr[0]][h][jj])
  68. kk++;
  69. if (kk == 1)
  70. {
  71. if (candi[i].first.size() + 2 < minlen)
  72. {
  73. minlen = candi[i].first.size() + 2;
  74. re.clear();
  75. vector<string>aa = candi[i].first;
  76. aa.push_back(candi[i].second[newstr[0]][h]);
  77. aa.push_back(endWord);
  78. re.push_back(aa);
  79. }
  80. else if (candi[i].first.size() + 2 == minlen)
  81. {
  82. vector<string>aa = candi[i].first;
  83. aa.push_back(candi[i].second[newstr[0]][h]);
  84. aa.push_back(endWord);
  85. re.push_back(aa);
  86. }
  87. }
  88. else if (candi[i].first.size() + kk + 1 <= minlen)
  89. {
  90. vector<string>aa = candi[i].first;
  91. aa.push_back(candi[i].second[newstr[0]][h]);
  92. map<char, vector<string>>cc = candi[i].second;
  93. cc[ss[0]].erase(find(cc[ss[0]].begin(),
  94. cc[ss[0]].end(), candi[i].second[newstr[0]][h]));
  95. newcandi.push_back(pair < vector<string>,
  96. map<char, vector<string>> >(aa, cc));
  97. }
  98. }
  99. }
  100. }
  101. }
  102. }
  103. candi = newcandi;
  104. }
  105. public:
  106. vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &wordList) {
  107. minlen = wordList.size() + 2;
  108. vector<pair<vector<string>, map<char,vector<string>>> >candi;
  109. int kkk=0;
  110. for (int i = 0; i < beginWord.length(); i++)
  111. if (beginWord[i] != endWord[i])
  112. kkk++;
  113. if (kkk==1)
  114. {
  115. vector<string>bb;
  116. bb.push_back(beginWord);
  117. bb.push_back(endWord);
  118. re.push_back(bb);
  119. return re;
  120. }
  121. vector<string>start;
  122. start.push_back(beginWord);
  123. map<char, vector<string>>bb;
  124. for (unordered_set<string>::iterator it = wordList.begin(); it != wordList.end(); it++)
  125. bb[(*it)[0]].push_back(*it);
  126. candi.push_back(pair<vector<string>, map<char, vector<string>>>(start,bb));
  127. while (!candi.empty()&&candi[0].first.size()+2<=minlen)
  128. {
  129. do_once(endWord, candi);
  130. }
  131. return re;
  132. }
  133. };
  134. int _tmain(int argc, _TCHAR* argv[])
  135. {
  136. string beginWord = "cet";
  137. string endWord = "ism";
  138. string words[599] = { "kid", "tag", "pup", "ail", "tun", "woo", "erg", "luz", "brr",
  139. "gay", "sip", "kay", "per", "val", "mes", "ohs", "now", "boa", "cet", "pal",
  140. "bar", "die", "war", "hay", "eco", "pub", "lob", "rue", "fry", "lit", "rex",
  141. "jan", "cot", "bid", "ali", "pay", "col", "gum", "ger", "row", "won", "dan",
  142. "rum", "fad", "tut", "sag", "yip", "sui", "ark", "has", "zip", "fez", "own",
  143. "ump", "dis", "ads", "max", "jaw", "out", "btu", "ana", "gap", "cry",
  144. "led", "abe", "box", "ore", "pig", "fie", "toy", "fat", "cal", "lie",
  145. "noh", "sew", "ono", "tam", "flu", "mgm", "ply", "awe", "pry", "tit",
  146. "tie", "yet", "too", "tax", "jim", "san", "pan", "map", "ski", "ova",
  147. "wed", "non", "wac", "nut", "why", "bye", "lye", "oct", "old", "fin",
  148. "feb", "chi", "sap", "owl", "log", "tod", "dot", "bow", "fob", "for",
  149. "joe", "ivy", "fan", "age", "fax", "hip", "jib", "mel", "hus", "sob",
  150. "ifs", "tab", "ara", "dab", "jag", "jar", "arm", "lot", "tom", "sax",
  151. "tex", "yum", "pei", "wen", "wry", "ire", "irk", "far", "mew", "wit",
  152. "doe", "gas", "rte", "ian", "pot", "ask", "wag", "hag", "amy", "nag",
  153. "ron", "soy", "gin", "don", "tug", "fay", "vic", "boo", "nam", "ave",
  154. "buy", "sop", "but", "orb", "fen", "paw", "his", "sub", "bob", "yea",
  155. "oft", "inn", "rod", "yam", "pew", "web", "hod", "hun", "gyp", "wei",
  156. "wis", "rob", "gad", "pie", "mon", "dog", "bib", "rub", "ere", "dig",
  157. "era", "cat", "fox", "bee", "mod", "day", "apr", "vie", "nev", "jam",
  158. "pam", "new", "aye", "ani", "and", "ibm", "yap", "can", "pyx", "tar",
  159. "kin", "fog", "hum", "pip", "cup", "dye", "lyx", "jog", "nun", "par",
  160. "wan", "fey", "bus", "oak", "bad", "ats", "set", "qom", "vat", "eat",
  161. "pus", "rev", "axe", "ion", "six", "ila", "lao", "mom", "mas", "pro",
  162. "few", "opt", "poe", "art", "ash", "oar", "cap", "lop", "may", "shy",
  163. "rid", "bat", "sum", "rim", "fee", "bmw", "sky", "maj", "hue", "thy",
  164. "ava", "rap", "den", "fla", "auk", "cox", "ibo", "hey", "saw", "vim",
  165. "sec", "ltd", "you", "its", "tat", "dew", "eva", "tog", "ram", "let",
  166. "see", "zit", "maw", "nix", "ate", "gig", "rep", "owe", "ind", "hog",
  167. "eve", "sam", "zoo", "any", "dow", "cod", "bed", "vet", "ham", "sis",
  168. "hex", "via", "fir", "nod", "mao", "aug", "mum", "hoe", "bah", "hal",
  169. "keg", "hew", "zed", "tow", "gog", "ass", "dem", "who", "bet", "gos",
  170. "son", "ear", "spy", "kit", "boy", "due", "sen", "oaf", "mix", "hep",
  171. "fur", "ada", "bin", "nil", "mia", "ewe", "hit", "fix", "sad", "rib",
  172. "eye", "hop", "haw", "wax", "mid", "tad", "ken", "wad", "rye", "pap",
  173. "bog", "gut", "ito", "woe", "our", "ado", "sin", "mad", "ray", "hon",
  174. "roy", "dip", "hen", "iva", "lug", "asp", "hui", "yak", "bay", "poi",
  175. "yep", "bun", "try", "lad", "elm", "nat", "wyo", "gym", "dug", "toe",
  176. "dee", "wig", "sly", "rip", "geo", "cog", "pas", "zen", "odd", "nan",
  177. "lay", "pod", "fit", "hem", "joy", "bum", "rio", "yon", "dec", "leg",
  178. "put", "sue", "dim", "pet", "yaw", "nub", "bit", "bur", "sid", "sun",
  179. "oil", "red", "doc", "moe", "caw", "eel", "dix", "cub", "end", "gem",
  180. "off", "yew", "hug", "pop", "tub", "sgt", "lid", "pun", "ton", "sol",
  181. "din", "yup", "jab", "pea", "bug", "gag", "mil", "jig", "hub", "low",
  182. "did", "tin", "get", "gte", "sox", "lei", "mig", "fig", "lon", "use",
  183. "ban", "flo", "nov", "jut", "bag", "mir", "sty", "lap", "two", "ins",
  184. "con", "ant", "net", "tux", "ode", "stu", "mug", "cad", "nap", "gun",
  185. "fop", "tot", "sow", "sal", "sic", "ted", "wot", "del", "imp", "cob",
  186. "way", "ann", "tan", "mci", "job", "wet", "ism", "err", "him", "all",
  187. "pad", "hah", "hie", "aim", "ike", "jed", "ego", "mac", "baa", "min",
  188. "com", "ill", "was", "cab", "ago", "ina", "big", "ilk", "gal", "tap",
  189. "duh", "ola", "ran", "lab", "top", "gob", "hot", "ora", "tia", "kip",
  190. "han", "met", "hut", "she", "sac", "fed", "goo", "tee", "ell", "not",
  191. "act", "gil", "rut", "ala", "ape", "rig", "cid", "god", "duo", "lin",
  192. "aid", "gel", "awl", "lag", "elf", "liz", "ref", "aha", "fib", "oho",
  193. "tho", "her", "nor", "ace", "adz", "fun", "ned", "coo", "win", "tao",
  194. "coy", "van", "man", "pit", "guy", "foe", "hid", "mai", "sup", "jay",
  195. "hob", "mow", "jot", "are", "pol", "arc", "lax", "aft", "alb", "len",
  196. "air", "pug", "pox", "vow", "got", "meg", "zoe", "amp", "ale", "bud",
  197. "gee", "pin", "dun", "pat", "ten", "mob" };
  198. unordered_set<string> wordList;
  199. for (int i = 0; i < 599; i++)
  200. wordList.insert(words[i]);
  201. Solution sl;
  202. vector<vector<string>>re=sl.findLadders(beginWord, endWord, wordList);
  203. system("pause");
  204. return 0;
  205. }

问题一 内存消耗太大

问题二 太慢

思路,换用双向广度优先搜索,从beginword和endword同时开始搜索,在找到第一个答案的那一层找到所有答案后即可返回。

  1. class Solution {
  2. public:
  3. vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &wordList) {
  4. vector<vector<string>>re;
  5. if (beginWord == endWord || beginWord.length() == 1)
  6. {
  7. vector<string>rr;
  8. rr.push_back(beginWord);
  9. rr.push_back(endWord);
  10. re.push_back(rr);
  11. return re;
  12. }
  13. int wl = beginWord.length();
  14. for (int i = 0; i < wl; i++)
  15. {
  16. string s1(beginWord), s2(endWord);
  17. s1.erase(i, 1); s2.erase(i, 1);
  18. if (s1 == s2)
  19. {
  20. vector<string>rr;
  21. rr.push_back(beginWord);
  22. rr.push_back(endWord);
  23. re.push_back(rr);
  24. return re;
  25. }
  26. }
  27. vector<string>words(wordList.begin(), wordList.end());
  28. map<pair<string,int>, vector<int>>changelist;
  29. for (int i = 0; i < words.size(); i++)
  30. {
  31. for (int j = 0; j < words[0].length(); j++)
  32. {
  33. string s = words[i];
  34. s.erase(j, 1);
  35. changelist[pair<string, int>(s,j)].push_back(i);
  36. }
  37. }
  38. vector<int>a, b;
  39. for (int i = 0; i < words.size(); i++)
  40. a.push_back(i);
  41. map<string, vector<vector<int>>>head, tail;
  42. head[beginWord].push_back(b);
  43. tail[endWord].push_back(b);
  44. bool flag = true;
  45. int k = 0;
  46. while (k < words.size() && flag)
  47. {
  48. k++;
  49. if (tail.size()>head.size())
  50. {
  51. map<string, vector<vector<int>>>newhead;
  52. for (map<string, vector<vector<int>>>::iterator ii = head.begin(); ii != head.end(); ii++)
  53. {
  54. for (int j = 0; j < ii->second.size(); j++)
  55. {
  56. for (int h = 0; h < wl; h++)
  57. {
  58. string s = ii->first;
  59. s.erase(h, 1);
  60. for (int f = 0; f < changelist[pair<string, int>(s,h)].size(); f++)
  61. {
  62. if (words[changelist[pair<string, int>(s,h)][f]] != ii->first)
  63. {
  64. vector<int>::iterator ite = find(ii->second[j].begin(),
  65. ii->second[j].end(), changelist[pair<string, int>(s,h)][f]);
  66. if (ite == ii->second[j].end())
  67. {
  68. map<string, vector<vector<int>>>::iterator nn =
  69. tail.find(words[changelist[pair<string, int>(s,h)][f]]);
  70. if (nn != tail.end())
  71. {
  72. for (int g = 0; g < nn->second.size(); g++)
  73. {
  74. set<int>aa;
  75. set<int>a1(ii->second[j].begin(), ii->second[j].end());
  76. set<int>a2(nn->second[g].begin(), nn->second[g].end());
  77. set_intersection(a1.begin(), a1.end(),
  78. a2.begin(), a2.end(), inserter(aa, aa.begin()));
  79. if (aa.empty() && (a1.size()>0 || a2.size()>0))
  80. {
  81. flag = false;
  82. vector<string>sl;
  83. sl.push_back(beginWord);
  84. for (int d = 0; d < ii->second[j].size(); d++)
  85. sl.push_back(words[ii->second[j][d]]);
  86. //sl.push_back(words[changelist[s][f]]);
  87. for (int d = nn->second[g].size() - 1; d >= 0; d--)
  88. sl.push_back(words[nn->second[g][d]]);
  89. sl.push_back(endWord);
  90. if (find(re.begin(), re.end(), sl) == re.end())
  91. re.push_back(sl);
  92. }
  93. }
  94. }
  95. if (flag)
  96. {
  97. vector<int>xx = ii->second[j];
  98. xx.push_back(changelist[pair<string, int>(s,h)][f]);
  99. newhead[words[changelist[pair<string, int>(s,h)][f]]].push_back(xx);
  100. }
  101. }
  102. }
  103. }
  104. }
  105. }
  106. }
  107. //f = !f;
  108. head = newhead;
  109. }
  110. else
  111. {
  112. map<string, vector<vector<int>>>newtail;
  113. for (map<string, vector<vector<int>>>::iterator ii = tail.begin(); ii != tail.end(); ii++)
  114. {
  115. for (int j = 0; j < ii->second.size(); j++)
  116. {
  117. for (int h = 0; h < wl; h++)
  118. {
  119. string s = ii->first;
  120. s.erase(h, 1);
  121. for (int f = 0; f < changelist[pair<string, int>(s,h)].size(); f++)
  122. {
  123. if (words[changelist[pair<string, int>(s,h)][f]] != ii->first)
  124. {
  125. vector<int>::iterator ite = find(ii->second[j].begin(), ii->second[j].end(),
  126. changelist[pair<string, int>(s,h)][f]);
  127. if (ite == ii->second[j].end())
  128. {
  129. map<string, vector<vector<int>>>::iterator nn = head.find(words[changelist[pair<string, int>(s, h)][f]]);
  130. if (nn != head.end())
  131. {
  132. for (int g = 0; g < nn->second.size(); g++)
  133. {
  134. set<int>aa;
  135. set<int>a1(ii->second[j].begin(), ii->second[j].end());
  136. set<int>a2(nn->second[g].begin(), nn->second[g].end());
  137. set_intersection(a1.begin(), a1.end(),
  138. a2.begin(), a2.end(), inserter(aa, aa.begin()));
  139. if (aa.empty() && (a1.size()>0 || a2.size()>0))
  140. {
  141. flag = false;
  142. vector<string>sl;
  143. sl.push_back(beginWord);
  144. for (int d = 0; d< nn->second[g].size(); d++)
  145. sl.push_back(words[nn->second[g][d]]);
  146. //sl.push_back(words[changelist[s][f]]);
  147. for (int d = ii->second[j].size() - 1; d >= 0; d--)
  148. sl.push_back(words[ii->second[j][d]]);
  149. sl.push_back(endWord);
  150. if (find(re.begin(), re.end(), sl) == re.end())
  151. re.push_back(sl);
  152. }
  153. }
  154. }
  155. if (flag)
  156. {
  157. vector<int>xx = ii->second[j];
  158. xx.push_back(changelist[pair<string, int>(s, h)][f]);
  159. newtail[words[changelist[pair<string, int>(s, h)][f]]].push_back(xx);
  160. }
  161. }
  162. }
  163. }
  164. }
  165. }
  166. }
  167. //f = !f;
  168. tail = newtail;
  169. }
  170. }
  171. return re;
  172. }
  173. };

accepted

发表评论

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

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

相关阅读

    相关 Word Ladder--LeetCode

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