[LeetCode]127. 单词接龙(java实现)转换为图论求最短路问题、bfs
1. 题目
2. 读题(需要重点注意的东西)
思路(bfs):
具体思路见[LeetCode]126. 单词接龙 II(java实现)转化成图论最短路问题,与其不同之处在于本题只需要返回最短的路径即可。
3. 解法
---------------------------------------------------解法---------------------------------------------------:
class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
Map<String,Integer> dist = new HashMap<>();
HashSet<String> set = new HashSet<>();
Queue<String> queue = new LinkedList<>();
// 初始化
dist.put(beginWord,1);
queue.offer(beginWord);
for(String s : wordList) set.add(s);
// bfs求最短路径
while(!queue.isEmpty()){
// 取出队头元素
String str = queue.poll();
// 单词转换,枚举这个单词的每一位
for(int i = 0;i < str.length();i++){
// 存储当前单词
StringBuilder sb = new StringBuilder(str);
// 将每一位上的字母换成26个英文字母中的一个,再转换成新的字符串,看是否在给定的wordList中
for(char c = 'a';c <= 'z';c++){
// 转换当前位上的字母为变量c
sb.setCharAt(i,c);
// 将变完的单词转换为String
String new_str = sb.toString();
// 如果新的单词在给定的wordList中,并且该单词还没有出现过,说明这个单词还没有被搜索过
if(set.contains(new_str) && !dist.containsKey(new_str)){
if(new_str.equals(endWord)) return dist.get(str) + 1;
// 将这个单词加到dist中,其路径长度为原单词路径长度+1
dist.put(new_str,dist.get(str) + 1);
// 将这个单词加到队列中,准备进行下一层bfs
queue.add(new_str);
}
}
}
}
return 0;
}
}
可能存在的问题:
4. 可能有帮助的前置习题
5. 所用到的数据结构与算法思想
- bfs
- dfs