126. Word Ladder II

Given two words (beginWord_and_endWord), and a dictionary's word list, find all shortest transformation sequence(s) frombeginWord_to_endWord, such that:

  1. Only one letter can be changed at a time

  2. Each transformed word must exist in the word list. Note that _beginWord _is _not _a transformed word.

Note:

  • Return an empty list if there is no such transformation sequence.

  • All words have the same length.

  • All words contain only lowercase alphabetic characters.

  • You may assume no duplicates in the word list.

  • You may assume _beginWord _and _endWord _are non-empty and are not the same.

Example 1:

Input:

beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]


Output:
[
  ["hit","hot","dot","dog","cog"],
  ["hit","hot","lot","log","cog"]
]

Example 2:

Thoughts:

  1. "Naive" Solution: Create a dictionary that maps <str word, List[List[str]]]> Solution lists. Initialize the layer[beginword] word as [[beginword]]. 1. Expanding the layer list as follows: 1. Having a childLayer which maps the layer for the next step 2. while current layer is not empty 1. for each w in layers keys: 2. if w is in the EndWord: res list record the results by taking all the elements of layer[w] 3. else for every position, flop the word w as neww. check if neww is in the wordList: add neww after every path in layer[w], add this result into childLayer[neww] 4. set layer to newLayer for the next iteration 5. remvoe all the keys from wordList that is in newlayers

  2. BFS + DFS:

    1. Shortest transformation: BFS to find the shortest path between start and end

    2. Find all the transformation: DFS with backtracking to find all the answer

Code: T:O(L^3*l) ? (L as wordList length, l as word length). S:O(L^3*l)?

Code: BFS + DFS

Last updated

Was this helpful?