#include <string>
#include <unordered_set>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
/*
Given two words (beginWord and endWord), and a dictionary's word list.
find the length of shortest transformation sequence from beginWord to
endWord, such that:
1: only one letter can be changed at a time.
2: Each intermediate word must exist in the word list.
For example:
Given, beginWord = "hit", endWord = "cog"
WordList = ["hot", "dot", "dog", "lot", "log"]
As one shortest transformation is "hit"-> "hot"->"dot"->"dog"->"cog"
return its length 5.
Note:
1: Return 0 if there is no such transformation sequence.
2: all words have the same length.
3: All words contain only lowercase alphabetic characters.
*/
// BFS
int ladderLength(string beginWord, string endWord, unordered_set<string>& wordList) {
struct wordAndDistance {
string word;
int distance;
};
queue<wordAndDistance> q;
wordList.erase(beginWord);
q.emplace(wordAndDistance{beginWord, 1});
while(!q.empty()) {
wordAndDistance f(q.front());
if(f.word == endWord) return f.distance;
string str = f.word;
for(int i = 0; i < str.size(); ++i) {
for(int j = 0; j < 26; ++j) {
str[i] = 'a' + j;
auto it(wordList.find(str));
if(it != wordList.end()) {
wordList.erase(it);
q.emplace(wordAndDistance{str, f.distance + 1});
}
}
str[i] = f.word[i];
}
q.pop();
}
return -1;
}
int main(void) {
string beginWord = "hit";
string endWord = "cog";
unordered_set<string> wordList{"hot", "dot", "dog", "lot", "log", "cog", "hit"};
cout << ladderLength(beginWord, endWord, wordList) << endl;
}
Further Optimized way: BFS from bi-directional and start from the fewer options' end
#include "header.h"
using namespace std;
int shortestLength(string start, string end, unordered_set<string>& dict) {
unordered_set<string> head;
head.insert(start);
unordered_set<string> tail;
tail.insert(end);
int length = 2;
while(!head.empty() && !tail.empty()) {
if(head.size() > tail.size()) swap(head, tail);
unordered_set<string> next;
for(auto iter = head.begin(); iter != head.end(); ++iter) {
string curr = *iter;
for(int j = 0; j < curr.size(); ++j) {
char c = curr[j];
for(char ch = 'a'; ch <= 'z'; ++ch) {
curr[j] = ch;
if(tail.find(curr) != tail.end()) return length;
if(dict.count(curr)) {
next.insert(curr);
dict.erase(curr);
}
}
curr[j] = c;
}
}
++length;
swap(head, next);
}
return 0;
}
int main(void) {
unordered_set<string> dict{"hot", "dot", "dog", "lot", "log", "hit"};
cout << shortestLength("hit", "cog", dict) << endl;
}