[LeetCode] 20 word Jielong II

subject Given two words (beginWord and endWor...
subject
thinking
code
Knowledge points involved

subject

Given two words (beginWord and endWord) and a dictionary wordList, find out all the shortest conversion sequences from beginWord to endWord. The conversion should follow the following rules:

1. Only one letter can be changed at a time. 2. The middle word in the conversion process must be the word in the dictionary. explain:

  • If no such conversion sequence exists, an empty list is returned.
  • All words have the same length.
  • All words are made up of lowercase letters only.
  • There are no duplicate words in the dictionary.
  • You can assume that beginWord and endWord are not empty, and they are different.

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"] ]

Example 2:

Input: beginWord = "hit" endWord = "cog" wordList = ["hot","dot","dog","lot","log"] Output: [] Explanation: endWord "cog" is not in the dictionary, so there is no conversion sequence that meets the requirements.

thinking

BFS Train of thought Description: when reaching the layer where the shortest path is located, record and output all qualified paths.

1. On the basis of word connection, the shortest path to be found needs to be stored; 2. The previous queue was only used to store the elements of each layer. Now we have to store the results after adding elements of each layer: "ab", "if", "CD", "AF", "IB", "if"}; (1) First layer: {"ab"} (2) The second layer: {"ab","af"}, {"ab","ib"} (3) The third layer: {"ab","af","if"}, {"ab","ib","if"} 3. If a word added in this layer conforms to the target word, the path is the shortest path, and this layer is the layer where the shortest path is located. However, the result cannot be returned directly at this time. The layer must be traversed completely, and all matching results of this layer must be added to the result set; 4. When adding words to each layer, they cannot be added directly to the total accessed word set. Each layer needs to have a separate set of words accessed by that layer. After the end of this layer, they will be added to the total accessed word set, because 3

code

package com.janeroad; import java.util.*; public class test8 { public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) { // Result set List<List<String>> res = new ArrayList<>(); Set<String> distSet = new HashSet<>(wordList); // The dictionary does not contain the target word if (!distSet.contains(endWord)) { return res; } // Visited word set: only the shortest path is found, so the previous words do not appear in the next layer Set<String> visited = new HashSet<>(); // Accumulate the result queue of each layer Queue<List<String>> queue= new LinkedList<>(); List<String> list = new ArrayList<>(Arrays.asList(beginWord)); queue.add(list); visited.add(beginWord); // Whether to reach the qualified layer: if a word added by the layer meets the target word, all solutions to the layer are the shortest path, and the loop is stopped boolean flag = false; while (!queue.isEmpty() && !flag) { // Result queue of the previous layer int size = queue.size(); // All elements added by this layer: each layer must add new words to the used word set after all results are added // If it is added directly to visited, the same adding behavior after adding the result of this layer will fail // For example, if the target word is encountered in this layer, there are two paths that can be encountered. However, if the first arrived one adds the word to the visited one, the second path cannot be added Set<String> subVisited = new HashSet<>(); for (int i = 0; i < size; i++) { List<String> path = queue.poll(); // Get the words of the layer above the path String word = path.get(path.size() - 1); char[] chars = word.toCharArray(); // Find the next eligible word for the word for (int j = 0; j < chars.length; j++) { char temp = chars[j]; for (char ch = 'a'; ch <= 'z'; ch++) { chars[j] = ch; if (temp == ch) { continue; } String str = new String(chars); // Meet the condition: previous layer in wordList & & has not been used if (distSet.contains(str) && !visited.contains(str)) { // Generate new path List<String> pathList = new ArrayList<>(path); pathList.add(str); // If the word is the target word: add the path to the result set and the query ends at that layer if (str.equals(endWord)) { flag = true; res.add(pathList); } // Add the path to the layer queue queue.add(pathList); // Add the word to the set of words accessed by the layer subVisited.add(str); } } chars[j] = temp; } } // Add all accessed words of this layer to the total accessed collection visited.addAll(subVisited); } return res; } public static void main(String[] args) { List<String> stringList = new LinkedList<String>(){{ add("hot"); add("dot"); add("dog"); add("lot"); add("cog"); }}; test8 test8=new test8(); System.out.println(test8.findLadders("hit","cog",stringList)); } }

Knowledge points involved

List<String> stringList = new LinkedList<String>(){{ add("a"); add("b"); add("c"); }};
  • The difference between List method and set method

(1) Duplicate object

The list method allows duplicate objects, while the set method does not allow duplicate objects

(2) null element

list can insert multiple null elements, while set only allows one null element to be inserted

(3) Is the container in order

list is an ordered container that keeps the order in which each element is inserted. That is to say, the output order is the input order, while the set method is an unordered container, which cannot guarantee the storage order of each element. TreeSet maintains a sort order through Comparator or Comparable

(4) Common implementation classes

The common implementation classes of List method are ArrayList, LinkedList and vector. Among them, ArrayList is the most popular, which provides random access to use indexes, while LinkedList is more suitable for situations that often need to add or remove elements from the List. Vector represents the underlying array, which is thread safe

The most popular implementation classes of Set methods are HashSet, LinkedHashSet, and TreeSet. The most popular is the HashSet based on the HashMap implementation; TreeSet also implements the SortedSet interface, so TreeSet is an ordered container to sort according to the definitions of compare() and compareTo()

26 May 2020, 05:04 | Views: 9600

Add new comment

For adding a comment, please log in
or create account

0 comments