Word Ladder II

Given two words (start_and_end), and a dictionary, find all shortest transformation sequence(s) fromstart_to_end, such that:

  1. Only one letter can be changed at a time

  2. Each intermediate word must exist in the dictionary

Notice

  • All words have the same length.

  • All words contain only lowercase alphabetic characters.

Example

Given: start ="hit" end ="cog" dict =["hot","dot","dog","lot","log"]

Return

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

Note

当要返回所有 path 的时候,细节处理就更多了。其实这题和 Longest Increasing Subsequence 的 follow-up ,返回所有 LIS 有相通的地方,都是维护一个 Directed Graph 关系并且从某一个终点进行 dfs 返回所有 valid path.

非常难了。有向图找最短距离用 BFS/有向图返回所有路径用 DFS 所以是DFS加上BFS

从起点到终点是BFS,终点到起点是DFS,需要记录:

不太清楚时间和空间复杂度

Code

Last updated