首页>itarticle>[leetcode] problem 126 – word ladder ii
[leetcode] problem 126 – word ladder ii
admin11月 13, 20200
Given two words (beginWord and endWord), and a dictionary’s word list, find all shortest transformation sequence(s) from beginWord to endWord, such that:
Only one letter can be changed at a time
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note
Return an empty list if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.
public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) { List<List<String>> results = new ArrayList<>(); List<String> result = new ArrayList<>();
if (!wordList.contains(endWord)) return results;
Map<String, List<String>> prev = new HashMap<>(); Map<String, Integer> count = new HashMap<>(); Set<String> dict = new HashSet<>();
dict.add(beginWord); dict.add(endWord); prev.putIfAbsent(beginWord, new ArrayList<>()); prev.putIfAbsent(endWord, new ArrayList<>()); count.put(endWord, 0);
for (String word : wordList) dict.add(word);
bfs(prev, count, dict, endWord);
// start -> end dfs(results, result, prev, count, beginWord, endWord);
近期评论