C++ 词语阶梯2

该博客讨论了如何使用C++解决从起始单词到结束单词的最短转换路径问题,其中每次转换只能改变一个字符,并且新单词必须存在于给定的词典中。例如,从'hit'到'cog'的最短路径包括'[“hit”, “hot”, “dot”, “dog”, “cog”]'和'[“hit”, “hot”, “lot”, “log”, “cog”]'。文章将探讨具体的算法实现和思路。" 108618975,8765213,Android编程:最佳5款移动开发应用,"['C++', 'Java', 'Python', 'Android开发', '移动应用']
摘要由CSDN通过智能技术生成

已知两个单词(分别是起始单词和结束单词),一个单词词典,根据转换规则计算所有的从起始单词到结束单词的最短转换路径。
转换规则如下:

  1. 在转换时,只能转换单词中的1个字符;
  2. 转换得到的新单词,必须在单词词典中。
    例如: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
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值