Approach
I was thinking a naive approach to build the graph for neighbor string first, and then try to do BFS. so the adjacency list part is TC O(MN^2), and the BFS part is O(M).
I saw a different method and think that it has lower complexity (actually not). We put the beginning number into the queue for BFS, and its neighbor is having at most O(25M) neighbors, since we can change one character among M to any other 25 characters, and we only need to hash the wordList and find if it is in the hash. If it is present in the hash we erase it and put it into the queue. In this case, all the element ahve at most 25M neighbor, and number of traversal is at most N, but the complexity is still O(M^2N) since hashing a length M string is O(M).
I also found one interesting solution for using bi-directional BFS, that is to spread only the smallest queue, in this case we can limit the spread, but it seems that hte runtime is similar in these caes, perhasp we need a case with a longer wordList.
Code-1: adjacency list + BFS
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
int endIdx = -1;
int n = wordList.size();
for(int i = 0 ; i < n ; ++i) {
if(endWord == wordList[i]) {
endIdx = i;
break;
}
}
if(endIdx == -1) return 0;
wordList.push_back(beginWord);
n = wordList.size();
int len = beginWord.size();
vector<vector<int>> adj(n);
for(int i = 0 ; i < n ; ++i) {
for(int j = i+1 ; j < n ; ++j) {
string& s1 = wordList[i];
string& s2 = wordList[j];
int cnt = 0;
for(int k = 0 ; k < len ; ++k) {
if(s1[k] != s2[k]) ++cnt;
if(cnt > 1) break;
}
if(cnt == 1) {
adj[i].push_back(j);
adj[j].push_back(i);
}
}
}
// BFS
queue<pair<int,int>> q;
vector<bool> visit(n, false);
q.push({n-1, 1});
while(!q.empty()) {
auto [idx, step] = q.front();
q.pop();
if(visit[idx]) continue;
visit[idx] = true;
for(const auto& next: adj[idx]) {
if(next == endIdx) return step+1;
q.push({next,step+1});
}
}
return 0;
}
};
Code-2: bi-directional BFS
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> dict(wordList.begin(), wordList.end());
if (!dict.count(endWord)) return 0;
unordered_set<string> front{beginWord}, back{endWord};
int step = 1;
while (!front.empty() && !back.empty()) {
if (front.size() > back.size())
swap(front, back);
unordered_set<string> next;
for (auto word : front) {
for (int i = 0; i < word.size(); ++i) {
char orig = word[i];
for (char c = 'a'; c <= 'z'; ++c) {
if (c == orig) continue;
word[i] = c;
if (back.count(word)) return step + 1;
if (dict.count(word)) {
next.insert(word);
dict.erase(word);
}
}
word[i] = orig;
}
}
front.swap(next);
++step;
}
return 0;
}
};