【无标题】

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

}

相关推荐
Dovis(誓平步青云)几秒前
切换语言后按钮被截断,本地化审计怎样发现长度风险
开发语言·前端·javascript·人工智能·机器学习·华为·harmonyos
小王C语言9 分钟前
Qt常用控件:按钮类控件,普通按键、单选、复选
开发语言·qt
街头便衣11 分钟前
OpenRouter周榜复算:164万亿token,输出2.55%,DeepSeek账单占1.4%
android·java·开发语言·人工智能·语言模型·开源
老王IT18 分钟前
PHP语言基础语法介绍
开发语言·php
2501_944521599 小时前
Ramda 跨端三方库仓颉适配全流程
开发语言·javascript·flutter·php
行思理9 小时前
go语言学习难度及适合学习的人群
开发语言·学习·golang
wangchunyu11410 小时前
JAVA CompletableFuture异步编程实战
java·开发语言·python
程序 代码狂人11 小时前
切片表与分区表的区别(数据开发面试版)
java·大数据·开发语言·数据仓库·算法
meiying883813 小时前
快递单号批量查询Python脚本:从手动到自动化的完整实现
开发语言·python·自动化