【无标题】

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

}

相关推荐
雨落倾城夏未凉2 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫3 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫4 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6254 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902114 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠4 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫6 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech7 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf8 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6259 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#