Word Ladder II
Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord to endWord.
(词语阶梯)
Note:
- Only one letter can be changed at a time.
- Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
- Return 0 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. BFS + DFS + BackTracking
下面这个解法最终并没有成功AC,主要就是超时(Time Limit Exceeded)的问题。先根据 BFS 找到最短的转换次数,然后在 DFS 进行求解的过程中将解法超过最短的转换次数的剪枝。具体实现过程如下:
1 | class Solution: |
2. BFS + DFS + BackTracking
下面这个方案是参照别人的解法,改进的地方就是在BFS的过程中,记录每个访问过的word距离beginWord的距离,显然 dis[beginword]=0, dis[endword]=minstep-1。然后逆向DFS(从终止点开始),对于每个每个即将要拓展的点最短路径必然满足的条件是:dis[word] + pathsize = minstep。具体实现过程如下:
1 | class Solution: |
3. BackTracking
另一种比较简单的做法,从 beginWord 出发,逐一修改 beginWord 中的字符,将第一次出现在 wordList 的词维护一个map保存,按同样的方式遍历这些词语直到找到 endWord。 然后从 endWord 出发逆向 DFS,具体实现过程如下:
1 | from collections import defaultdict |
Note: 这里dictionary = set(wordList)很重要,不然也会超时(Time Limit Exceeded)。set和list可以自由转换,在删除list中多个/海量重复元素时,可以先转换成set,然后再转回list并排序(set没有排序),此种方法不仅方便且效率较高。