博文中会简要介绍Leetcode P0126题目分析及解题思路。
“Word Ladder II”是p0127的变形题,这道题是一道相对较难的广度优先搜索题目,利用初始的word
数组构造一个无向图,每个结点代表一个单词,然后从起始单词所代表的结点开始BFS,然后记录所有同层的解即可。
GGiven 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.
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:
最基本的思路是通过word
数组来构建一个无向图,然后从起始单词所指向的结点使用广度优先搜索,这样一来一旦搜索到和结束单词一样的单词,此时的路径长度一定是最短的,而所有和这条路径一样短的其他路径必然与这个路径处在同一层。
并且我们可以通过反向映射,即将单词改变一个字母后可能产生的形态(即Wildcards)映射到可以具有这样形态的实际单词上,来优化BFS对邻接结点的遍历。
以下是Java的题解代码实现。