题目
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.
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.
Example 1:
Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
Example 2:
Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Output: 0
Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
题意:
给定一个开始字串,给定一个结尾字串,在给定一个词典,我们需要通过这个词典,将开始字串转换为结尾字串
每次只能转变一个字符,这个字符必须在词典里
问最少需要多少步转换
无法转换的返回0
解答
这题我使用BFS来进行解答,我们需要有两个集,一个是已经访问过的词典集reach,一个是未访问的(也就是wordList)
我们先将beginWord加入访问过的词典集reach。之后每次都执行这样的步骤:
寻找reach集可以变化位的词(也就是reach集中词改变一个字母可以得到的词),将词加入reach集,并从wordList中删除
不断执行,直到找到endWord,中间reach集变换了几次,就是需要几次转化。
以题目示例1说明
step 1:
reach={"hit"} wordLIist={"hot","dot","dog","lot","log","cog"}
step2
reach={"hot"} wordLIist={"dot","dog","lot","log","cog"}
step3
reach={"dot","lot"} wordLIist={"dog","log","cog"}
step4
reach={"dog","log"} wordLIist={"cog"}
step5
reach={"cog"} wordLIist={}
遇到的一个小问题:超时 TLE
经过研究 ,ArrayList调用 contains 复杂度是O(n),所以需要用一个更好的数据结构去代替,我使用了 Hashmap
成功AC。
代码:
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
HashSet<String> dict = new HashSet<>(); //用hashmap来替代list,降低查找复杂度
for(String word : wordList) {
dict.add(word);
}
if(endWord.contains(endWord)==false) return 0;
int distance=1;
List<String> reach=new ArrayList<String>();
reach.add(beginWord);
while(true){
if(reach.contains(endWord)) return distance;
int bound=reach.size();
for(int j=0;j<bound;j++){
for(int x=0;x<beginWord.length();x++){
char []temp=reach.get(0).toCharArray();
for(char y='a';y<='z';y++){
temp[x]=y;
String s=String.valueOf(temp);
if(dict.contains(s)){
reach.add(s);
dict.remove(s);
}
}
}
reach.remove(0);
}
distance++;
if(reach.size()==0) return 0;
}
}
}
本文介绍了一种使用广度优先搜索(BFS)算法解决单词转换问题的方法,旨在找到从开始单词到目标单词的最短转换路径。通过将单词视为图中的节点,每一步转换视为边,利用BFS遍历图的特性,可以有效地找到最短路径。
1万+

被折叠的 条评论
为什么被折叠?



