codekofi
← All problems

Problem 126

Hard

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1int solution(const string& start, const string& target,
2 const vector<string>& words) {
3
4 unordered_set<string> pool(words.begin(), words.end());
5
6 if (!pool.count(target)) {
7 return 0;
8 }
9
10 queue<string> edge;
11 edge.push(start);
12
13 int steps = 1;
14
15 while (!edge.empty()) {
16
17 int wide = edge.size();
18
19 for (int i = 0; i < wide; i++) {
20
21 string word = edge.front();
22 edge.pop();
23
24 if (word == target) {
25 return steps;
26 }
27
28 for (int j = 0; j < (int)word.size(); j++) {
29
30 char had = word[j];
31
32 for (char c = 'a'; c <= 'z'; c++) {
33
34 word[j] = c;
35
36 if (pool.count(word)) {
37 pool.erase(word);
38 edge.push(word);
39 }
40 }
41
42 word[j] = had;
43 }
44 }
45
46 steps++;
47 }
48
49 return 0;
50}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.