# Word Ladder (Length of shortest chain to reach a target word)

Given a dictionary, and two words ‘start’ and ‘target’ (both of same length). Find length of the smallest chain from ‘start’ to ‘target’ if it exists, such that adjacent words in the chain only differ by one character and each word in the chain is a valid word i.e., it exists in the dictionary. It may be assumed that the ‘target’ word exists in dictionary and length of all dictionary words is same.

Example:

```Input:  Dictionary = {POON, PLEE, SAME, POIE, PLEA, PLIE, POIN}
start = TOON
target = PLEA
Output: 7
Explanation: TOON - POON - POIN - POIE - PLIE - PLEE - PLEA```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

The idea is to use BFS. We start from the given start word, traverse all words that adjacent (differ by one character) to it and keep doing so until we find the target word or we have traversed all words.

Below are implementation of above idea.

## C++

 `// C++ program to find length of the shortest chain ` `// transformation from source to target ` `#include ` `using` `namespace` `std; ` ` `  `// Returns length of shortest chain to reach 'target' from 'start' ` `// using minimum number of adjacent moves.  D is dictionary ` `int` `shortestChainLen(string start, string target, set& D) ` `{ ` ` `  `    ``// If the target string is not ` `    ``// present in the dictionary ` `    ``if` `(D.find(target) == D.end()) ` `        ``return` `0; ` ` `  `    ``// To store the current chain length ` `    ``// and the length of the words ` `    ``int` `level = 0, wordlength = start.size(); ` ` `  `    ``// Push the starting word into the queue ` `    ``queue Q; ` `    ``Q.push(start); ` ` `  `    ``// While the queue is non-empty ` `    ``while` `(!Q.empty()) { ` ` `  `        ``// Increment the chain length ` `        ``++level; ` ` `  `        ``// Current size of the queue ` `        ``int` `sizeofQ = Q.size(); ` ` `  `        ``// Since the queue is being updated while ` `        ``// it is being traversed so only the ` `        ``// elements which were already present ` `        ``// in the queue before the start of this ` `        ``// loop will be traversed for now ` `        ``for` `(``int` `i = 0; i < sizeofQ; ++i) { ` ` `  `            ``// Remove the first word from the queue ` `            ``string word = Q.front(); ` `            ``Q.pop(); ` ` `  `            ``// For every character of the word ` `            ``for` `(``int` `pos = 0; pos < wordlength; ++pos) { ` ` `  `                ``// Retain the original character ` `                ``// at the current position ` `                ``char` `orig_char = word[pos]; ` ` `  `                ``// Replace the current character with ` `                ``// every possible lowercase alphabet ` `                ``for` `(``char` `c = ``'a'``; c <= ``'z'``; ++c) { ` `                    ``word[pos] = c; ` ` `  `                    ``// If the new word is equal ` `                    ``// to the target word ` `                    ``if` `(word == target) ` `                        ``return` `level + 1; ` ` `  `                    ``// Remove the word from the set ` `                    ``// if it is found in it ` `                    ``if` `(D.find(word) == D.end()) ` `                        ``continue``; ` `                    ``D.erase(word); ` ` `  `                    ``// And push the newly generated word ` `                    ``// which will be a part of the chain ` `                    ``Q.push(word); ` `                ``} ` ` `  `                ``// Restore the original character ` `                ``// at the current position ` `                ``word[pos] = orig_char; ` `            ``} ` `        ``} ` `    ``} ` ` `  `    ``return` `0; ` `} ` ` `  `// Driver program ` `int` `main() ` `{ ` `    ``// make dictionary ` `    ``set D; ` `    ``D.insert(``"poon"``); ` `    ``D.insert(``"plee"``); ` `    ``D.insert(``"same"``); ` `    ``D.insert(``"poie"``); ` `    ``D.insert(``"plie"``); ` `    ``D.insert(``"poin"``); ` `    ``D.insert(``"plea"``); ` `    ``string start = ``"toon"``; ` `    ``string target = ``"plea"``; ` `    ``cout << ``"Length of shortest chain is: "` `         ``<< shortestChainLen(start, target, D); ` `    ``return` `0; ` `} `

## Java

 `// Java program to find length of the shortest chain ` `// transformation from source to target ` `import` `java.util.*; ` ` `  `class` `GFG ` `{ ` ` `  `// Returns length of shortest chain  ` `// to reach 'target' from 'start' ` `// using minimum number of adjacent moves. ` `// D is dictionary ` `static` `int` `shortestChainLen(String start,  ` `                            ``String target,  ` `                            ``Set D) ` `{ ` ` `  `    ``// If the target String is not ` `    ``// present in the dictionary ` `    ``if` `(!D.contains(target)) ` `        ``return` `0``; ` ` `  `    ``// To store the current chain length ` `    ``// and the length of the words ` `    ``int` `level = ``0``, wordlength = start.length(); ` ` `  `    ``// Push the starting word into the queue ` `    ``Queue Q = ``new` `LinkedList<>(); ` `    ``Q.add(start); ` ` `  `    ``// While the queue is non-empty ` `    ``while` `(!Q.isEmpty()) ` `    ``{ ` ` `  `        ``// Increment the chain length ` `        ``++level; ` ` `  `        ``// Current size of the queue ` `        ``int` `sizeofQ = Q.size(); ` ` `  `        ``// Since the queue is being updated while ` `        ``// it is being traversed so only the ` `        ``// elements which were already present ` `        ``// in the queue before the start of this ` `        ``// loop will be traversed for now ` `        ``for` `(``int` `i = ``0``; i < sizeofQ; ++i)  ` `        ``{ ` ` `  `            ``// Remove the first word from the queue ` `            ``char` `[]word = Q.peek().toCharArray(); ` `            ``Q.remove(); ` ` `  `            ``// For every character of the word ` `            ``for` `(``int` `pos = ``0``; pos < wordlength; ++pos) ` `            ``{ ` ` `  `                ``// Retain the original character ` `                ``// at the current position ` `                ``char` `orig_char = word[pos]; ` ` `  `                ``// Replace the current character with ` `                ``// every possible lowercase alphabet ` `                ``for` `(``char` `c = ``'a'``; c <= ``'z'``; ++c) ` `                ``{ ` `                    ``word[pos] = c; ` ` `  `                    ``// If the new word is equal ` `                    ``// to the target word ` `                    ``if` `(String.valueOf(word).equals(target)) ` `                        ``return` `level + ``1``; ` ` `  `                    ``// Remove the word from the set ` `                    ``// if it is found in it ` `                    ``if` `(!D.contains(String.valueOf(word))) ` `                        ``continue``; ` `                    ``D.remove(String.valueOf(word)); ` ` `  `                    ``// And push the newly generated word ` `                    ``// which will be a part of the chain ` `                    ``Q.add(String.valueOf(word)); ` `                ``} ` ` `  `                ``// Restore the original character ` `                ``// at the current position ` `                ``word[pos] = orig_char; ` `            ``} ` `        ``} ` `    ``} ` ` `  `    ``return` `0``; ` `} ` ` `  `// Driver code ` `public` `static` `void` `main(String[] args) ` `{ ` `    ``// make dictionary ` `    ``Set D = ``new` `HashSet(); ` `    ``D.add(``"poon"``); ` `    ``D.add(``"plee"``); ` `    ``D.add(``"same"``); ` `    ``D.add(``"poie"``); ` `    ``D.add(``"plie"``); ` `    ``D.add(``"poin"``); ` `    ``D.add(``"plea"``); ` `    ``String start = ``"toon"``; ` `    ``String target = ``"plea"``; ` `    ``System.out.print(``"Length of shortest chain is: "` `        ``+ shortestChainLen(start, target, D)); ` `} ` `} ` ` `  `// This code is contributed by PrinciRaj1992 `

## C#

 `// C# program to find length of the shortest chain ` `// transformation from source to target ` `using` `System; ` `using` `System.Collections.Generic; ` ` `  `class` `GFG ` `{ ` ` `  `// Returns length of shortest chain  ` `// to reach 'target' from 'start' ` `// using minimum number of adjacent moves. ` `// D is dictionary ` `static` `int` `shortestChainLen(String start,  ` `                            ``String target,  ` `                            ``HashSet D) ` `{ ` ` `  `    ``// If the target String is not ` `    ``// present in the dictionary ` `    ``if` `(!D.Contains(target)) ` `        ``return` `0; ` ` `  `    ``// To store the current chain length ` `    ``// and the length of the words ` `    ``int` `level = 0, wordlength = start.Length; ` ` `  `    ``// Push the starting word into the queue ` `    ``List Q = ``new` `List(); ` `    ``Q.Add(start); ` ` `  `    ``// While the queue is non-empty ` `    ``while` `(Q.Count != 0) ` `    ``{ ` ` `  `        ``// Increment the chain length ` `        ``++level; ` ` `  `        ``// Current size of the queue ` `        ``int` `sizeofQ = Q.Count; ` ` `  `        ``// Since the queue is being updated while ` `        ``// it is being traversed so only the ` `        ``// elements which were already present ` `        ``// in the queue before the start of this ` `        ``// loop will be traversed for now ` `        ``for` `(``int` `i = 0; i < sizeofQ; ++i)  ` `        ``{ ` ` `  `            ``// Remove the first word from the queue ` `            ``char` `[]word = Q.ToCharArray(); ` `            ``Q.RemoveAt(0); ` ` `  `            ``// For every character of the word ` `            ``for` `(``int` `pos = 0; pos < wordlength; ++pos) ` `            ``{ ` ` `  `                ``// Retain the original character ` `                ``// at the current position ` `                ``char` `orig_char = word[pos]; ` ` `  `                ``// Replace the current character with ` `                ``// every possible lowercase alphabet ` `                ``for` `(``char` `c = ``'a'``; c <= ``'z'``; ++c) ` `                ``{ ` `                    ``word[pos] = c; ` ` `  `                    ``// If the new word is equal ` `                    ``// to the target word ` `                    ``if` `(String.Join(``""``, word).Equals(target)) ` `                        ``return` `level + 1; ` ` `  `                    ``// Remove the word from the set ` `                    ``// if it is found in it ` `                    ``if` `(!D.Contains(String.Join(``""``, word))) ` `                        ``continue``; ` `                    ``D.Remove(String.Join(``""``, word)); ` ` `  `                    ``// And push the newly generated word ` `                    ``// which will be a part of the chain ` `                    ``Q.Add(String.Join(``""``, word)); ` `                ``} ` ` `  `                ``// Restore the original character ` `                ``// at the current position ` `                ``word[pos] = orig_char; ` `            ``} ` `        ``} ` `    ``} ` `    ``return` `0; ` `} ` ` `  `// Driver code ` `public` `static` `void` `Main(String[] args) ` `{ ` `    ``// make dictionary ` `    ``HashSet D = ``new` `HashSet(); ` `    ``D.Add(``"poon"``); ` `    ``D.Add(``"plee"``); ` `    ``D.Add(``"same"``); ` `    ``D.Add(``"poie"``); ` `    ``D.Add(``"plie"``); ` `    ``D.Add(``"poin"``); ` `    ``D.Add(``"plea"``); ` `    ``String start = ``"toon"``; ` `    ``String target = ``"plea"``; ` `    ``Console.Write(``"Length of shortest chain is: "` `        ``+ shortestChainLen(start, target, D)); ` `} ` `} ` ` `  `// This code is contributed by PrinciRaj1992 `

Output:

```Length of shortest chain is: 7
```

Time Complexity of the above code is O(n²m) where n is the number of entries originally in the dictionary and m is the size of the string

Thanks to Gaurav Ahirwar and Rajnish Kumar Jha for above solution.

My Personal Notes arrow_drop_up

Improved By : princiraj1992

Article Tags :
Practice Tags :

10

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.