赞
踩
时间超时
class Solution { public: bool isvalue(string s1, string s2) { int len = s1.size(); int count = 0; for (int i = 0; i<len; ++i) { if (s1[i] != s2[i]) ++count; } if (count == 1) return true; return false; } int counta = 1; int BFS(string beginWord, string endWord, vector<string>& wordList, map<string, vector<string> > neigh, map<string, int>& flag) { deque<pair<string,int> > S; S.push_back(pair<string, int>(beginWord,1) );//当前节点进入队列中 while (!S.empty()) { string temp = S.front().first;//当前遍历的节点 int step = S.front().second; vector<string> svec = neigh[temp]; S.pop_front(); if (temp == endWord) { return step; } for (int i = 0; i<svec.size(); ++i) { string s1 = svec[i]; if (flag[s1] == 0) { //++counta; flag[s1] = 1; S.push_back(pair<string,int>(s1,step+1)); } } } return 0; } int ladderLength(string beginWord, string endWord, vector<string>& wordList) { map<string, vector<string> > neigh; map<string, int> flag;//标志 int len = wordList.size(); vector<string> v_sa; neigh[beginWord] = v_sa; for (int i = 0; i < len; ++i) { if (isvalue(beginWord, wordList[i])) neigh[beginWord].push_back(wordList[i]); } for (int i = 0; i < len; ++i) { vector<string> v_s; string temp1 = wordList[i]; neigh[temp1] = v_s; } for (int i = 0; i<len; ++i) { string temp1 = wordList[i]; for (int j =i+1; j<len; ++j) { if (isvalue(temp1, wordList[j])) { neigh[temp1].push_back(wordList[j]); neigh[wordList[j]].push_back(temp1); } } } for (int i = 0; i < len; ++i) flag[wordList[i]] = 0; auto res=BFS(beginWord, endWord, wordList, neigh, flag); return res; } };
使用另一种方法也是广度优先遍历
class Solution { public: int ladderLength(string beginWord, string endWord, vector<string>& wordList) { //使用一定的set和排序 unordered_set<string> wordlist(wordList.begin(), wordList.end()); if (wordlist.count(endWord) == 0) return 0; deque<string> S; S.push_back(beginWord); int l = beginWord.size(); int step = 0; while (!S.empty()) { ++step; int sslen = S.size(); for (int i = 0; i<sslen; ++i) { string temp = S.front(); S.pop_front(); if (temp == endWord) return step; for (int i = 0; i<l; ++i) { string bianhua = temp; for (char a = 'a'; a<'z'; ++a) { bianhua[i] = a; if (wordlist.count(bianhua) != 0) { S.push_back(bianhua); wordlist.erase(bianhua); } } } } } return 0; } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。