当前位置:网站首页>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;
}
}边栏推荐
- 2. login and exit function development
- 4.分类管理业务开发
- H5网页如何在微信中自定义分享链接
- 栈题目:括号的分数
- Spark提交参数--files的使用
- 【Energy Reports期刊发表】2022年能源与环境工程国际会议(CFEEE 2022)
- Machine learning perceptron and k-nearest neighbor
- [energy reports] International Conference on energy and environmental engineering in 2022 (cfeee 2022)
- Uniapp implements the function of clicking to make a call
- Leetcode - 498: traversée diagonale
猜你喜欢
随机推荐
2.登陆退出功能开发
Using pandas to read SQL server data table
SQL Server AVG function rounding
4. classification management business development
JMeter接口测试工具基础 — Badboy工具
Flink cluster construction and enterprise level yarn cluster construction
抓包工具charles實踐分享
[ei sharing] the 6th International Conference on ship, ocean and Maritime Engineering in 2022 (naome 2022)
【IEEE出版】2022年工业自动化,机器人与控制工程国际会议(IARCE 2022)
web网站开发,图片懒加载
Flink checkPoint和SavePoint
记录一下MySql update会锁定哪些范围的数据
Web site development, lazy image loading
2022全网最全最细的jmeter接口测试教程以及接口测试流程详解— JMeter测试计划元件(线程<用户>)
tf.contrib.layers.batch_norm
SSM integration
Distributed transaction principle and solution
The difference between the sleep () method and the wait () method of a thread
Image click enlargement and adaptive size in the applet rich text
百度网盘下载一直请求中问题解决









