当前位置:网站首页>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;
}
}边栏推荐
- How to customize sharing links in wechat for H5 web pages
- 使用swiper左右轮播切换时,Swiper Animate的动画失效,怎么解决?
- tf. errors
- 2022 International Symposium on intelligent robots and systems (isoirs 2022)
- Safety and food security for teachers and students of the trapped Yingxi middle school
- 消息队列的作用
- Six states of threads
- 百度网盘下载一直请求中问题解决
- 如何在一个页面上使用多个KindEditor编辑器并将值传递到服务器端
- 24. 图像拼接大作业
猜你喜欢

24. 图像拼接大作业

leetCode-498: 对角线遍历

Baidu online disk download has been in the process of requesting solutions

2022全网最全最细的jmeter接口测试教程以及接口测试流程详解— JMeter测试计划元件(线程<用户>)

Uniapp implements the function of clicking to make a call

JMeter接口测试工具基础 — Badboy工具

Customize the toolbars of the kindeditor editor. Items removes unnecessary toolbars or retains some toolbars

2. login and exit function development

leetCode-223: 矩形面积

Petit guide de construction rapide du bras mécanique (II): application du bras mécanique
随机推荐
Process and multithreading
Safety and food security for teachers and students of the trapped Yingxi middle school
Learning to organize using kindeditor rich text editor in PHP
Niuke-top101-bm28
How to use multiple kindeditor editors on a page and pass values to the server
Leetcode-1051: height checker
包装类型的缓存机制
Uniapp implements the function of clicking to make a call
Flink集群搭建以及企业级yarn集群搭建
Common methods of thread scheduling
Caching mechanism for wrapper types
leetCode-498: 对角线遍历
1. project environment construction
Distribute proofs of manuscripts by scanning
Difference between package type and basic type
leetCode-1089: 复写零
cuda runtime error (801) : Raw out
【资源分享】2022年第五届土木,建筑与环境工程国际会议(ICCAEE 2022)
[EI分享] 2022年第六届船舶,海洋与海事工程国际会议(NAOME 2022)
牛客-TOP101-BM29