/*
Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that:
Only one letter can be changed at a time
Each intermediate word must exist in the dictionary
For example,
Given:
start = "hit"
end = "cog"
dict = ["hot","dot","dog","lot","log"]
As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
Note:
Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
*/
#include <iostream>
#include <string>
#include <unordered_set>
#include <queue>
using namespace std;
int shortest(const string& s, const string& t, unordered_set<string>& dict) {
if(s.size() != t.size()) return 0;
if(s == t) return 0; //
unordered_set<string> used;
int level1, level2;
queue<string> q;
q.push(s);
used.insert(s);
level1 = 1;
level2 = 0;
int jumps = 1;
while(!q.empty()) {
string st = q.front();
q.pop();
level1--;
if(st == t) return jumps;
for(int i=0; i<st.size(); i++) {
string copy(st);
for(int j=1; j<=26; j++) {
copy[i] = 'a' + j - 1;
if(st == copy) continue;
if(dict.find(copy) == dict.end()) continue;
if(used.find(copy) != used.end()) continue;
q.push(copy);
used.insert(copy);
level2++;
}
}
if(level1 == 0) {
jumps++;
level1 = level2;
level2 = 0;
}
}
return 0;
}
int main()
{
unordered_set<string> dict = {"ab", "ac", "xc"};
cout << shortest("ab", "xc", dict);
}