【无标题】

#include

#include

#include

#include <unordered_set>

#include

using namespace std;

bool isOneDiff(const string &a, const string &b) {

if (a.size() != b.size()) return false;

int cnt = 0;

for (int i = 0; i < a.size(); i++) {

if (ai != bi) cnt++;

if (cnt > 1) return false;

}

return cnt == 1;

}

int main() {

string beginWord, endWord;

cin >> beginWord >> endWord;

复制代码
// 特殊情况:起点和终点是同一个单词
if (beginWord == endWord) {
    cout << 1 << endl;
    return 0;
}

int n;
cin >> n;
unordered_set<string> wordSet;
for (int i = 0; i < n; i++) {
    string s;
    cin >> s;
    wordSet.insert(s);
}

// BFS 队列:当前单词 + 当前步数
queue<pair<string, int>> q;
unordered_set<string> visited;

q.push({beginWord, 1});
visited.insert(beginWord);

while (!q.empty()) {
    auto cur = q.front();
    q.pop();
    string currentWord = cur.first;
    int step = cur.second;

    // 遍历所有单词,寻找相邻单词
    for (const string &word : wordSet) {
        if (!visited.count(word) && isOneDiff(currentWord, word)) {
            // 检查这个单词能否一步到达 endWord
            if (isOneDiff(word, endWord)) {
                cout << step + 2 << endl;
                return 0;
            }
            visited.insert(word);
            q.push({word, step + 1});
        }
    }
    // 额外检查:当前单词能否直接一步到达 endWord
    if (isOneDiff(currentWord, endWord)) {
        cout << step + 1 << endl;
        return 0;
    }
}

// 无法到达
cout << -1 << endl;
return 0;

}

相关推荐
XBodhi.2 小时前
Visual Studio C++ 语法错误: 缺少“;”(在“return”的前面)
开发语言·c++·visual studio
LSssT.2 小时前
【01】Python 机器学习
开发语言·python
l1t3 小时前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程39-40
开发语言·python
曾阿伦3 小时前
Python 搭建简易HTTP服务
开发语言·python·http
YG亲测源码屋3 小时前
java配置环境变量、jdk环境变量配置、java环境变量设置方法
java·开发语言
MIUMIUKK3 小时前
从语法层面,看懂 Python 的特殊处
java·开发语言·python
FlyWIHTSKY3 小时前
TS、TSX、JS、JSX 文件扩展名详解
开发语言·javascript·ecmascript
着迷不白3 小时前
第一部分:认识python
开发语言·python