-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathword_conversion.cpp
73 lines (64 loc) · 1.9 KB
/
word_conversion.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include "word_conversion.h"
#include <queue>
#include <unordered_set>
bool IsOneCharDiff(const std::string& current, const std::string& word)
{
auto diff = 0;
for (auto i = 0; i < current.length(); ++i)
{
if (current[i] != word[i])
{
diff++;
}
}
return diff == 1;
}
int WordConversionStep(const std::string& begin, const std::string& target, std::vector<std::string>& words)
{
// Convert the word list into a set for faster lookup
const std::unordered_set<std::string> word_set(words.begin(), words.end());
if (!word_set.count(target))
{
return 0;
}
// Queue to perform BFS
std::queue<std::string> search_queue;
// Keep track of visited words to avoid infinite loop
std::unordered_set<std::string> visited;
search_queue.push(begin);
visited.insert(begin);
auto step = 0;
while (!search_queue.empty())
{
// Perform search on all words in the queue
for (auto i = 0; i < static_cast<int>(search_queue.size()); ++i)
{
auto current = search_queue.front();
search_queue.pop();
// If the current word is the target, return the number of steps
if (current == target)
{
return step;
}
// Search for all words that differ by a single character
for (const auto& word : word_set)
{
if (!visited.count(word) && IsOneCharDiff(current, word))
{
search_queue.push(word);
visited.insert(word);
}
}
}
step++;
}
// If the target word is not reachable, return 0
return 0;
}
// using namespace std;
//
// int solution(string begin, string target, vector<string> words)
// {
// int answer = WordConversionStep(begin, target, words);
// return answer;
// }