当前位置:网站首页>126. word Solitaire II BFS
126. word Solitaire II BFS
2022-06-24 10:33:00 【Empress Yu】
126. The word chain II
Press the dictionary
wordListComplete from wordbeginWordTo wordsendWordconversion , A representation of this process Conversion sequence It's formally likebeginWord -> s1 -> s2 -> ... -> skThis sequence of words , And satisfy :
- There is only a single letter between each pair of adjacent words .
- Every word in the conversion process
si(1 <= i <= k) It has to be a dictionarywordListThe words in . Be careful ,beginWordIt doesn't have to be a dictionarywordListThe words in .sk == endWordHere are two words for you
beginWordandendWord, And a dictionarywordList. Please find out and return all frombeginWordToendWordOf The shortest transformation sequence , If there is no such conversion sequence , Return an empty list . Each sequence should be in a list of words[beginWord, s1, s2, ..., sk]Form return of .Example 1:
Input :beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"] Output :[["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]] explain : There is 2 The shortest transformation sequence : "hit" -> "hot" -> "dot" -> "dog" -> "cog" "hit" -> "hot" -> "lot" -> "log" -> "cog"Example 2:
Input :beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"] Output :[] explain :endWord "cog" Not in the dictionary wordList in , So there is no conversion sequence that meets the requirements .Tips :
1 <= beginWord.length <= 5endWord.length == beginWord.length1 <= wordList.length <= 500wordList[i].length == beginWord.lengthbeginWord、endWordandwordList[i]It's made up of lowercase lettersbeginWord != endWordwordListAll the words in Different from each othersource : Power button (LeetCode)
link :https://leetcode.cn/problems/word-ladder-ii
Copyright belongs to the network . For commercial reprint, please contact the official authority , Non-commercial reprint please indicate the source .
The result of doing the question
Failure , Repeatedly adjust BFS,DFS, Or not through timeout
Method :BFS
This question card is very strict , insane TLE, You can't live without optimization , After reading the solution to the problem, I changed my way to understand it easily
1. Special judgement , If the destination is not in the list, return
2. Reverse image , It is convenient to find the starting point backwards ; If it is a positive graph , There may be a dead end , Cause extra time , Inverse graph is also a way of pruning
3. Check for presence a->b Access to , If b Point is the first visit , You also need to search b Is the inverse graph of the end point , Otherwise, you need to see if the steps are the same , If the number of steps is the same , It can also be used as one of the schemes to reach this point
4. If this floor is over , Has reached the end , No need to keep looking , The number of subsequent steps will increase , Not the best answer , End directly
5. May not find a viable path , Returns an empty
6. If you can find it, look in the opposite direction , Insert the header through the double ended queue , Obtain the positive solution ( Or you can just use the normal list and vice versa )
public class Solution {
List<List<String>> ans = new ArrayList<>();
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) {
Set<String> nodes = new HashSet<>(wordList);
// The end is not wordList Returns an empty
if(!nodes.contains(endWord)) return ans;
Map<String,Set<String>> reGraph = new HashMap<>();// Reverse image
Set<String> orgin = new HashSet<>(wordList);
Queue<String> queue = new LinkedList<>();
queue.offer(beginWord);
// Assumed length is x There is already a viable path , There is no need to check the length x+1 Of
while (!queue.isEmpty() && !reGraph.containsKey(endWord)){
int size = queue.size();
// Same layer node
Set<String> line = new HashSet<>();
// Sequence find the next point
for(int i = 0; i < size; i++){
String a = queue.poll();
// Original point list , Find all the next accessible points
for(String b:orgin){
if(!diffOne(a,b)) continue;
// If the number of steps just ahead is the same as now ( Same floor ) Or visit for the first time
if(line.contains(b) || nodes.contains(b)){
reGraph.putIfAbsent(b,new HashSet<>());
reGraph.get(b).add(a);
line.add(b);
// First visit delete node , Keep looking for the way
if(nodes.remove(b)){
queue.offer(b);
}
}
}
}
}
// It is necessary to determine whether a feasible path
if(!reGraph.isEmpty()){
Deque<String> deque = new LinkedList<>();
deque.push(endWord);
dfs(reGraph,deque,beginWord,endWord);
}
return ans;
}
private void dfs(Map<String,Set<String>> graph, Deque<String> deque,String start,String end){
if(start.equals(end)){
ans.add(new ArrayList<>(deque));
return;
}
for(String pre:graph.get(end)){
deque.addFirst(pre);
dfs(graph,deque,start,pre);
deque.removeFirst();
}
}
private boolean diffOne(String a, String b){
int n = a.length();
int diff = 0;
for(int i = 0; i < n&&diff<2; i++){
if(a.charAt(i)!=b.charAt(i)) ++diff;
}
return diff == 1;
}
}边栏推荐
- 24. 图像拼接大作业
- Machine learning - principal component analysis (PCA)
- 2022全网最全最细的jmeter接口测试教程以及接口测试流程详解— JMeter测试计划元件(线程<用户>)
- Leetcode interview question 01.05: primary editing
- 【JS逆向分享】某个网站社区信息
- leetCode-1823: 找出游戏的获胜者
- How can I solve the problem that the swiper animation animation fails when switching between left and right rotations of the swiper?
- 分布式系统你必须了解的点-CAP
- Appium automation test foundation - mobile end test environment construction (I)
- 百度网盘下载一直请求中问题解决
猜你喜欢
随机推荐
Quick completion guide for mechanical arm (II): application of mechanical arm
numpy. logical_ or
线程池的状态
Image click enlargement and adaptive size in the applet rich text
The difference between static link library and dynamic link library
2. login and exit function development
Spark submission parameter -- use of files
【资源分享】2022年环境工程与生物技术国际会议(CoEEB 2022)
[IEEE publication] 2022 International Conference on intelligent transportation and future travel (cstfm 2022)
顺丰科技智慧物流校园技术挑战赛(2022/06/19)【AK】
机械臂速成小指南(一):机械臂发展概况
Uniapp develops wechat official account, and the drop-down box selects the first one in the list by default
Leetcode-498: diagonal traversal
機械臂速成小指南(二):機械臂的應用
正规方程、、、
希尔排序图文详解+代码实现
web网站开发,图片懒加载
Uniapp implementation forbids video drag fast forward
自定义kindeditor编辑器的工具栏,items即去除不必要的工具栏或者保留部分工具栏
leetCode-498: 对角线遍历









