已知两个单词(分别是起始单词和结束单词),一个单词词典,根据转换规则计算所有的从起始单词到结束单词的最短转换路径。
转换规则如下:
- 在转换时,只能转换单词中的1个字符;
- 转换得到的新单词,必须在单词词典中。
例如:beginWord=“hit”; endWord=“cog”,wordList=[“hot”,“dot”,“dog”,“lot”,“log”,“cog”]
最短转换路径:[“hit”,“hot”,“dot”,“dog”,“cog”],[“hit”,“hot”,“lot”,“log”,“cog”]
#include<string>
#include<vector>
#include<map>
bool connect(const std::string& word1, const std::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(std::string& beginWord, std::vector<std::string>& wordList, std::map<std::string, std::vector<std::string>> &graph)
{
int has_begin_word = 0;
for (int i = 0; i < wordList.size(); i++)
{
if (beginWord==wordList[i])
{
has_begin_word = 1;
}
graph[wordList[i]] = std::vector<std::string>();
}
for (int i = 0; i < wordList.size(); i++)
{
for (int j = i