Word Ladder
Question
Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
- 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.
For example,
Given:
beginWord = “hit”
endWord = “cog”
wordList = [“hot”,”dot”,”dog”,”lot”,”log”,”cog”]
As one shortest transformation is “hit” -> “hot” -> “dot” -> “dog” -> “cog”,
return its length 5.
Note:
- 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.
Analysis
所有的词可以构成一张图,每个词相当于一个顶点,彼此间相差一个字母的词相连,利用BFS遍历整张图,第一次碰到endWord时的距离即使最短的。
- 由于正常查找toAdd的方式会TLE,所以在每次得到toAdd的时候,将较小的集合作为begin,较大的集合作为end
- 题中给出的List查找效率较低(我也不知道什么效率低,大概是查找吧),所以也会导致TLE,在一开始的时候就要创建Set
Code
Normal Solution
|
|
Two-end Solution
|
|
Word Ladder II
Question
Given two words (beginWord and endWord), and a dictionary’s word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
- 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.
For example,
Given:
beginWord = “hit”
endWord = “cog”
wordList = [“hot”,”dot”,”dog”,”lot”,”log”,”cog”]
Return
[
["hit","hot","dot","dog","cog"],
["hit","hot","lot","log","cog"]
]
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.
Analysis
- 利用BFS,找到所有词间可能的关系,利用DFS,找到相应的路径并添加到res中
- BFS遍历过程同Word Ladder I,只不过不需要再找到endWord时候退出循环
- nodeneighbors 保存每个节点的邻居节点
- distance 保存当前节点与beginWord相差的字母个数,只有在BFS过程中第一次遇到某词才进行添加,后续不需要更新,因为第一次碰到是距离beginWord距离最短的
- DFS遍历过程中同Backtracking,在每次调用初始像solution加入当前节点,在碰到endWord时,向res加入solution,加入solution时需要new ArrayList\
(Solution) - DFS过程中,当下一节点与当前节点距离beginWord距离相差1时递归调用,且在完成一次递归调用的时候,删除在此次调用时加入的节点
Code
|
|