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

In this problem, we are given a dictionary and two words ‘start’ and ‘target’. Our task is to generate a chain (ladder) from start work to target word, the chain is created such that each word differs the other character by only one word and the word should also exist in the dictionary. The target word exists in the dictionary and also the length of all words is the same. The program will return the length of the shortest path from start to target.

Let’s take an example to understand the problem,

## Input

Dictionary = {‘HEAL’, ‘HATE’, ‘HEAT’, ‘TEAT’, ‘THAT’, ‘WHAT’ , ‘HAIL’ ‘THAE’}
Start = ‘HELL’
Target = ‘THAE’

## Output

6

## Explanation

HELL - HEAL - HEAT - TEAT - THAT - THAE

To solve this problem, we will do Breadth-first search of the dictionary. Now, step by step find all elements that are one letter away from the previous character. And create a ladder from start to target.

Program to show the implementation of our solution,

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
int wordLadder(string start, string target, set<string>& dictionary) {
if (dictionary.find(target) == dictionary.end())
return 0;
int level = 0, wordlength = start.size();
++level;
for (int i = 0; i < sizeOfLadder; ++i) {
for (int pos = 0; pos < wordlength; ++pos) {
char orig_char = word[pos];
for (char c = 'a'; c <= 'z'; ++c) {
word[pos] = c;
if (word == target)
return level + 1;
if (dictionary.find(word) == dictionary.end())
continue;
dictionary.erase(word);
}
word[pos] = orig_char;
}
}
}
return 0;
}
int main() {
set<string> dictionary;
dictionary.insert("heal");
dictionary.insert("heat");
dictionary.insert("teat");
dictionary.insert("that");
dictionary.insert("what");
dictionary.insert("thae");
dictionary.insert("hlle");
string start = "hell";
string target = "thae";
cout<<"Length of shortest chain from '"<<start<<"' to '"<<target<<"' is: "<<wordLadder(start, target, dictionary);
return 0;
}

## Output

Length of shortest chain from 'hell' to 'thae' is: 6

Updated on: 17-Jul-2020

182 Views