Understanding the Problem
You are given a startWord
, a targetWord
, and a list of allowed wordList
. The goal is to transform startWord
to targetWord
such that:
- Only one letter can be changed at a time.
- Each transformed word must exist in the
wordList
.
- You must find all the shortest transformation sequences.
Why Use BFS First?
BFS is ideal here because it explores all nodes level by level. This helps us find the shortest path from startWord
to targetWord
. As we explore, we also keep track of:
- Which word was reached from which other word (edges)
- The level (number of steps) required to reach each word
We stop BFS once we reach the targetWord
level, ensuring we only explore the shortest paths.
Building the Transformation Graph
We consider two words connected if they differ by only one character. For example, "hit" → "hot" is a valid transformation. We build this graph during BFS traversal.
When No Transformation Exists
If the targetWord
is never reached during BFS, it means there’s no possible transformation. In this case, we return an empty list.
Collecting All Shortest Paths
Once the BFS is complete, we use DFS or backtracking to find all shortest transformation sequences. Starting from the targetWord
, we backtrack to the startWord
using the level information (so we only go from higher to lower levels), ensuring that only the shortest sequences are considered.
Edge Case: Words Not in List
If either startWord
or targetWord
is not in the wordList
, we must handle it properly. Usually, startWord
is not required in the list, but targetWord
must be in it to allow transformation.