您好,登錄后才能下訂單哦!
#include<iostream>
#include<set>
#include<queue>
#include<vector>
#include<string>
#include<map>
using namespace std;
bool connect(string &word1,string &word2)
{
int cnt = 0;
for(int i = 0; i < word1.length(); i++)
if(word1[i] != word2[i])
cnt++;
return cnt == 1;
}
void construct_graph(string &beginword,vector<string> &wordlist, map<string ,vector<string> > &graph)
{
wordlist.push_back(beginword);
for(int i = 0; i < wordlist.size(); i++)
graph[wordlist[i]] = vector<string>();
for(int i = 0; i < wordlist.size(); i++)
for(int j = i+1; j < wordlist.size(); j++)
{
if(connect(wordlist[i],wordlist[j]))
{
graph[wordlist[i]].push_back(wordlist[j]);
graph[wordlist[j]].push_back(wordlist[i]);
}
}
}
int BFS_wordlist(string &beginword, string &endword, map<string, vector<string> > &graph)
{
queue<pair<string,int> > q;
set<string> visit;
q.push(make_pair(beginword,1));
visit.insert(beginword);
while(!q.empty())
{
string node = q.front().first;
int step = q.front().second;
q.pop();
if(node == endword)
{
return step;
}
vector<string> brothers = graph[node];
for(int i = 0; i < brothers.size(); i++)
{
if(visit.find(brothers[i]) == visit.end())
{
q.push(make_pair(brothers[i], step+1));
visit.insert(brothers[i]);
}
}
}
return 0;
}
int main()
{
string beginword,endword;
vector<string> wordlist;
map<string ,vector<string> > graph;
wordlist.push_back("hot");
wordlist.push_back("dot");
wordlist.push_back("dog");
wordlist.push_back("lot");
wordlist.push_back("log");
wordlist.push_back("cog");
cin>>beginword;
cin>>endword;
construct_graph(beginword,wordlist,graph);
cout<<BFS_wordlist(beginword,endword,graph);
return 0;
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。