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的運行后的情況 
新聞熱點
疑難解答