BFS的题目,一开始做的时候,我是判断出栈元素和数组里的元素是否距离为1,超时。思考了一下觉得是判断是否距离为1处,所有换过一个字母的字符串都要和每个wordList里元素比较,太耗时了。
所以直接建立一个set,所有换过一个字母的字符串直接在set里找,找到了就直接erase,方便不少。
class Solution { public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { unordered_set<string> s(wordList.begin(),wordList.end()); queue<string> q({beginWord}); int count=1; while (!q.empty()){ int cnt=q.size(); for (int k=0;k<cnt;++k){ string tmp=q.front(); q.pop(); if (tmp==endWord) return count; for (char ch='a';ch<'z';++ch){ for (int i=0;i<tmp.size();++i){ string x=tmp; x[i] = ch; if (s.find(x)!=s.end()){ q.push(x); s.erase(x); } } } } ++count; } return 0; } };
Word Ladder II 就是上一题的升级版,实质一样。bfs做,把变化的路径 vector<string> 放到 queue 里。本题需要剪枝,如果当前size比最小size大,直接break。
class Solution { public: vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) { int min_len=INT_MAX; unordered_set<string> s(wordList.begin(),wordList.end()); vector<vector<string>> res; queue<vector<string>> q; q.push(vector<string>({beginWord})); while (!q.empty()){ vector<string> tmp=q.front(); q.pop(); if (tmp.size()>min_len) break; string cur=tmp.back(); s.erase(cur); if (cur==endWord){ if (tmp.size()<=min_len){ res.push_back(tmp); min_len = tmp.size(); }else break; } for (int i=0;i<cur.size();++i){ for (char ch='a';ch<='z';++ch){ string str=cur; str[i] = ch; if (s.count(str)){ tmp.push_back(str); q.push(tmp); tmp.pop_back(); } } } } return res; } };