Word Ladder II

Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from start to end, such that:

Only one letter can be changed at a time

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"]
  ]

Solution:

这道题的难点就是求出所有的最短路径的解决方案,可以使用BFS来求解,但是为了套用模版,使一般的题目都可以模式化,要知道很多面试这个题没做过,需要做3,4个小时,结果面试过程中需要半个小时做完,所以我跟人的方法就是尽量选择容易记忆,容易总结,容易成为模版的方法,所以碰见了球解决方案个数的,我多半使用DFS,但是这道题直接使用DFS是很不直接的,可以先设置两个集合,一个是保持所有单词的出入度的哈希表,一个是从开始的节点到当前节点的距离。然后在做DFS。利用临时变量path, 从后往前的添加,这个题我自己没有做出来,职能搬运九张算法的方案了。

Last updated

Was this helpful?