【BFS】127. 单词接龙(待优化【建图】)
class Solution {
public:
bool is_cross(string &word1, string &word2){
bool flag = true;
for(int i=0;i<word_length;++i)
if(word1[i] != word2[i])
if(flag)
flag = false;
else
return false;
return true;
}
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
word_length = beginWord.size();
list_length = wordList.size();
queue <int> s_q;
int dp[list_length+1];
bool is_go[list_length+1];
for(int i=0;i<=list_length;++i){
is_go[i] = false;
dp[i] = 0;
}
s_q.push(0);
is_go[0] = true;
dp[0] = 1;
while(!s_q.empty()){
int cur_loc = s_q.front();
s_q.pop();
string cur_str;
if(cur_loc == 0)
cur_str = beginWord;
else
cur_str = wordList[cur_loc - 1];
if(cur_str == endWord)
return dp[cur_loc];
for(int i=0;i<list_length;++i){
if(is_cross(cur_str, wordList[i])){
if(dp[i+1] == 0)
dp[i+1] = dp[cur_loc] + 1;
else
dp[i+1] = min(dp[i+1], dp[cur_loc]+1);
if(!is_go[i+1]){
is_go[i+1] = true;
s_q.push(i+1);
}
}
}
}
return 0;
}
private:
int word_length;
int list_length;
};
图(快了一丢丢):
class Solution {
public:
bool is_cross(string &word1, string &word2){
bool flag = true;
for(int i=0;i<word_length;++i)
if(word1[i] != word2[i])
if(flag)
flag = false;
else
return false;
return true;
}
void buildGraph(vector<string>& wordList){
graph = vector<vector<int>>(list_length, vector<int>());
for(int i=0;i<list_length;++i){
for(int j=i+1;j<list_length;++j){
if(is_cross(wordList[i],wordList[j])){
graph[i].push_back(j);
graph[j].push_back(i);
// cout << i << "," << j << " ";
}
}
// cout << endl;
}
}
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
wordList.push_back(beginWord);
list_length = wordList.size();
word_length = beginWord.size();
buildGraph(wordList);
int dp[list_length];
int beginIndex = list_length - 1;
int endIndex = -1;
for(int i=0;i<list_length;++i){
dp[i] = -1;
if(endWord == wordList[i])
endIndex = i;
}
if(endIndex == -1)
return 0;
queue<int> q;
dp[beginIndex] = 1;
q.push(beginIndex);
while(!q.empty()){
int curIndex = q.front();
q.pop();
for(auto g : graph[curIndex]){
if(dp[g] == -1){
dp[g] = dp[curIndex] + 1;
q.push(g);
} else {
dp[g] = min(dp[curIndex] + 1, dp[g]);
}
}
}
return dp[endIndex]==-1?0:dp[endIndex];
}
private:
int word_length;
int list_length;
vector<vector<int>> graph;
};

浙公网安备 33010602011771号