17.22. Word Transformer
Description
Given two words of equal length that are in a dictionary, write a method to transform one word into another word by changing only one letter at a time. The new word you get in each step must be in the dictionary.
Write code to return a possible transforming sequence. If there are more that one sequence, any one is ok.
Example 1:
Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output: ["hit","hot","dot","lot","log","cog"]
Example 2:
Input: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log"] Output: [] Explanation: endWord "cog" is not in the dictionary, so there's no possible transforming sequence.
Solutions
Solution 1: DFS
We define an answer array ans
, initially containing only beginWord
. Then we define an array vis
to mark whether the words in wordList
have been visited.
Next, we design a function dfs(s)
, which represents whether we can successfully convert s
to endWord
starting from s
. If successful, return True
, otherwise return False
.
The specific implementation of the function dfs(s)
is as follows:
- If
s
equalsendWord
, the conversion is successful, returnTrue
; - Otherwise, we traverse each word
t
inwordList
. Ift
has not been visited and there is only one different character betweens
andt
, then we markt
as visited, addt
toans
, and then recursively calldfs(t)
. IfTrue
is returned, the conversion is successful, we returnTrue
, otherwise we removet
fromans
and continue to traverse the next word; - If all the words in
wordList
have been traversed and no convertible word is found, the conversion fails, we returnFalse
.
Finally, we call dfs(beginWord)
. If True
is returned, the conversion is successful, we return ans
, otherwise return an empty array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|