【无标题】

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

}

相关推荐
「QT(C++)开发工程师」1 小时前
C++ 11 常用for循环
开发语言·c++
我还记得那天2 小时前
0 初识C++
开发语言·c++
FfHUCisI2 小时前
Go 编译过程全景
开发语言·后端·golang
FfHUCisI2 小时前
Golang 语法分析与 AST:Parser 与 go/ast
开发语言·后端·golang
lemon_sjdk3 小时前
ObjectProperty
java·开发语言·算法
大模型码小白3 小时前
Spring AI Tool 实现自然语言操作 MySQL 数据库详解
服务器·开发语言·数据库·人工智能·python·mysql·spring
hh9503 小时前
Agent Plan x DeepSeek Harness:Agent 供应链安全与第三方插件审计
java·开发语言·安全·agent plan·adg成都社区·adg社区
Behaviour3 小时前
Unity UI循环列表UIScrollViewContent实现
ui·unity·c#·游戏引擎
「QT(C++)开发工程师」3 小时前
C++ std::move 详解
开发语言·c++