You may change one letter at a time, and each intermediate word must exist in the word list.
Return the length of the shortest transformation sequence, or 0 if impossible.
Model the relationships explicitly, then choose BFS, DFS, or union find based on the question. Track visited state so cycles do not create repeated work.
Examples
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: 5
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] Output: 0
Constraints
- 1 <= beginWord.length <= 10
- All words have the same length.
- 1 <= wordList.length <= 5000