https://leetcode.com/PRoblems/word-ladder/
ac代码餐卡 博主:陆草纯 地址:http://www.cnblogs.com/ganganloveu/p/4125695.html 直接采用bfs, 注意判重,解map,set结构
struct Node{ string word; int len; Node(string w, int l): word(w), len(l) {}};class Solution {public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { int len1 = beginWord.size(); int len2 = endWord.size(); if(len1 != len2) return 0; unordered_set<string> wordDict; // 字典集合 vector<string>::iterator it = wordList.begin(); while(it != wordList.end()) { wordDict.insert(*it); ++it; } if(wordDict.find(endWord) == wordDict.end()) return 0; queue<Node*> que; unordered_map<string,bool> mp; // 记录是否访问到了 Node* beginNode = new Node(beginWord, 1); que.push(beginNode); mp[beginWord] = true; while(!que.empty()) { Node* frontNode = que.front(); que.pop(); string frontWord = frontNode->word; int len = frontWord.size(); // for(int i=0;i<len;i++) { for(char c = 'a'; c <= 'z'; c++) { if(c == frontWord[i]) continue; string frontWordTmp = frontWord; frontWordTmp[i] = c; //相邻的string if(frontWordTmp == endWord) return frontNode->len + 1; // 字典中有此相邻单词,并且没有被访问到 if(wordDict.find(frontWordTmp) != wordDict.end()) { if(mp[frontWordTmp] == false) { Node* tmp = new Node(frontWordTmp, frontNode->len + 1); mp[frontWordTmp] = true; que.push(tmp); } } } } // end for } // end while return 0; }};https://leetcode.com/problems/word-ladder-ii/
如果采用上面的思路,会出现错误 一是每个string的前一个stirng可能有多个 而是超时问题
本题的ac思路参考 博主:会咬人的兔子 地址:http://www.cnblogs.com/93scarlett/p/6376822.html
先用bfs构建出一个邻接表
具体是每一string,替换一个字母可以有哪些string同时记录每一个字符能从开始字符到其的步骤数
最后采用dfs,对上诉构造出来的图进行遍历,求解
ac代码如如下 通过Debug,next和step的运行后的情况
新闻热点
疑难解答