1. DFS Exhaustive Transformation Search
Intuition
Use Depth-First Search with backtracking to explore all valid one-letter transformations from beginWord towards endWord. Track visited words to avoid infinite loops. Maintain a minimum path length; return the shortest path length found, or 0 if unreachable.
Algorithm
- If
endWordis not inwordList, return 0. - Store
wordListin a setdict. - Initialize
visitedset. - Define
dfs(currWord, depth): - If
currWord == endWord, updateminLen = min(minLen, depth). - For each word
windictnot invisiteddiffering by exactly 1 letter: -
visited.add(w) -
dfs(w, depth + 1) -
visited.remove(w)(backtrack) - Return
minLen.
#include <iostream>#include <vector>#include <string>#include <unordered_set>#include <algorithm>#include <climits> bool differsByOne(const std::string& a, const std::string& b) { int diff = 0; for (int i = 0; i < (int)a.size(); ++i) { if (a[i] != b[i]) { if (++diff > 1) return false; } } return diff == 1;} void dfs(const std::string& curr, const std::string& target, int depth, const std::vector<std::string>& words, std::vector<bool>& visited, int& minDepth) { if (depth >= minDepth) return; if (curr == target) { minDepth = depth; return; } for (int i = 0; i < (int)words.size(); ++i) { if (!visited[i] && differsByOne(curr, words[i])) { visited[i] = true; dfs(words[i], target, depth + 1, words, visited, minDepth); visited[i] = false; } }} int ladderLengthDFS(std::string beginWord, std::string endWord, std::vector<std::string>& wordList) { int minDepth = INT_MAX; std::vector<bool> visited(wordList.size(), false); dfs(beginWord, endWord, 1, wordList, visited, minDepth); return minDepth == INT_MAX ? 0 : minDepth;} int main() { std::vector<std::string> wordList = {"hot","dot","dog","lot","log","cog"}; std::cout << "Word Ladder (DFS): " << ladderLengthDFS("hit", "cog", wordList) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N!) worst case as all permutation paths of words are explored. - Space complexity:
O(N) for the recursion stack and visited set.