G-30 : Word Ladder-II(Hash Map)
Given a list indicating words and two separate words, startWord and targetWorda list of distinct words with comparable lengths. Determine which transformation sequences from startWord to targetWord are the shortest. They can be returned in any feasible order. The following requirements must be considered in this problem statement: Examples: Example 1: Input: startWord = “der”, targetWord = “dfs”, wordList = {“des”,”der”,”dfr”,”dgt”,”dfs”} Output: [ [ “der”, “dfr”, “dfs” ], [ “der”, “des”, “dfs”] ] Explanation: The length of the smallest transformation sequence here is 3. Following are the only two shortest ways to get to the targetWord from the startWord : “der” -> ( replace ‘r’ by ‘s’ ) -> “des” -> ( replace ‘e’ by ‘f’ ) -> “dfs”. “der” -> ( replace ‘e’ by ‘f’ ) -> “dfr” -> ( replace ‘r’ by ‘s’ ) -> “dfs”. Example 2: Input: startWord = “gedk”, targetWord= “geek” wordList = {“geek”, “gefk”} Output: [ [ “gedk”, “geek” ] ] Explanation: The length of the smallest transformation sequence here is 2. Following is the only shortest way to get to the targetWord from the startWord : “gedk” -> ( replace ‘d’ by ‘e’ ) -> “geek”. Intuition: The idea behind applying the BFS traversal strategy to these types of issues is that, if we pay close attention, we continue to replace the characters one by one, giving the impression that we are going level-wise to get to the targetWord. It is evident from the example below that there are two ways to get to the targetWord. Since we require all of the shortest sequences to get to the destination word, unlike the prior case, we continue the traversal for as many instances of the targetWord as possible rather than stopping it at the first occurrence. The only difficulty here is that, even if a word matches the changed word during character replacement, we do not have to remove it from the wordList right away. Rather, we remove it whenever the traversal for a specific level is over, enabling us to investigate every potential route. This enables us to find several sequences using related words that lead to the targetWord. We can infer from the preceding image that there are two shortest feasible sequences that lead to the word “cog.” C++ Java Output: der des dfs der dfr dfs
G-30 : Word Ladder-II(Hash Map) Read More »