帮我用cpp写一个能找到并显示最短单词阶梯的程序
时间: 2023-12-07 16:02:48 浏览: 47
好的,以下是用 C++ 编写的找到最短单词阶梯的程序:
```c++
#include <iostream>
#include <fstream>
#include <queue>
#include <map>
#include <vector>
#include <string>
using namespace std;
bool is_adjacent(const string& s1, const string& s2) {
if (s1.length() != s2.length() || s1 == s2)
return false;
int cnt = 0;
for (int i = 0; i < s1.length(); ++i) {
if (s1[i] != s2[i])
++cnt;
if (cnt > 1)
return false;
}
return cnt == 1;
}
void display_ladder(const map<string, string>& trace, const string& start, const string& end) {
if (trace.find(end) == trace.end()) {
cout << "No ladder found." << endl;
return;
}
vector<string> ladd;
ladd.push_back(end);
string cur = end;
while (cur != start) {
cur = trace.at(cur);
ladd.push_back(cur);
}
for (int i = ladd.size() - 1; i >= 0; --i)
cout << ladd[i] << " ";
cout << endl;
}
void find_ladder(const string& filename, const string& start, const string& end) {
ifstream fin(filename);
if (!fin) {
cerr << "Cannot open file " << filename << endl;
return;
}
vector<string> words;
while (!fin.eof()) {
string word;
fin >> word;
words.push_back(word);
}
fin.close();
map<string,
相关推荐
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)