【无标题】

#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;

}

相关推荐
benchmark_cc1 天前
如何用 Python + QuantDash 快速构建高胜率“配对交易(Pairs Trading)”策略?
开发语言·人工智能·python·pandas·量化交易·quantdash
程序员无隅1 天前
Coding Agent 为什么压缩上下文后还能继续工作?上下文模块设计拆解
java·开发语言·数据库
Python+991 天前
Java 枚举类(Enum)详解:从基础到高级应用
java·开发语言·python
二炮手亮子1 天前
浅记java线程池
java·开发语言
rockey6271 天前
基于AScript的JavaScript脚本语言发布啦
javascript·c#·.net·js·script
zmzb01031 天前
C++课后习题训练记录Day157
开发语言·c++
dunge20261 天前
2026年7月最新ChatGPT Plus / Pro 与 Codex:当 AI Agent 最新5.6版本来袭,必须理解事务、幂等与补偿
开发语言·人工智能·python
LuoCore1 天前
AForge.Video.FFMPEG.dll加载失败解决指南
c#
吴可可1231 天前
C#元组解构实现变量交换
c#
爱吃牛肉的大老虎1 天前
rust基础之环境搭建
java·开发语言·rust