思维导图攻破算法难题
算法思路视频讲解请点击——> b站鲁班代师讲解视频
更多精彩视频(Letecode笔试高频题、互联网大厂笔试刷题)请在bilibili搜索鲁班代师,然后搜索题号就可以,关注不走丢,感谢。
欢迎批评指正、探讨!
class Solution {
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList)
{
wordList.add(beginWord);
HashMap<String,ArrayList<String>> graph = new HashMap<>();
connectGraph(beginWord, wordList, graph);
HashMap<String, Integer> distance = Bfs(beginWord, graph);
LinkedList<String> result = new LinkedList<>();
List<List<String>> results = new ArrayList<>();
Dfs(beginWord, endWord, graph, distance, result, results);
return results;
}
public ArrayList<String> getNext( String word, List<String> wordList)
{
char[] wordArr = word.toCharArray();
Set<String> wordListDict = new HashSet<>(wordList);
ArrayList<String> next = new ArrayList<>();
for(char cur = 'a'; cur <= 'z'; cur++)
{
for(int i = 0; i < word.length(); i++)
{
if(wordArr[i] != cur)
{
char tmp = wordArr[i];
wordArr[i] = cur;
if(wordListDict.contains(String.valueOf(wordArr)))
{
next.add(String.valueOf(wordArr));
}
wordArr[i] = tmp;
}
}
}
return next;
}
public void connectGraph(String beginWord, List<String> wordList, HashMap<String,ArrayList<String>> graph)
{
for(int i = 0; i < wordList.size(); i++)
{
graph.put(wordList.get(i),new ArrayList<>());
}
for(int i = 0; i < wordList.size(); i++)
{
graph.put(wordList.get(i),getNext(wordList.get(i),wordList));
}
}
public HashMap<String,Integer> Bfs(String beginWord, HashMap<String,ArrayList<String>> graph)
{
HashMap<String,Integer> shortestLen = new HashMap<>();
shortestLen.put(beginWord,0);
Queue<String> queue = new LinkedList<>();
queue.add(beginWord);
HashSet<String> visit = new HashSet<>();
visit.add(beginWord);
while(!queue.isEmpty())
{
String cur = queue.poll();
for(String str : graph.get(cur))
{
if(!visit.contains(str))
{
shortestLen.put(str,shortestLen.get(cur) + 1);
queue.add(str);
visit.add(str);
}
}
}
return shortestLen;
}
public void Dfs(String curWord, String endWord, HashMap<String,ArrayList<String>> graph, HashMap<String, Integer> distance,LinkedList<String> Solution, List<List<String>> res)
{
Solution.add(curWord);
if(endWord.equals(curWord))
{
res.add(new LinkedList<String>(Solution));
}
else
{
for(String str : graph.get(curWord))
{
if(distance.get(str) == distance.get(curWord) + 1)
{
Dfs(str, endWord, graph, distance, Solution, res);
}
}
}
Solution.pollLast();
}
}