Introduction
Word Ladder is one of the most famous BFS shortest path problems.
You are given:
- beginWord
- endWord
- wordList
Goal:
Find the length of the shortest transformation sequence from beginWord to endWord.
Rules:
- Change only one character at a time.
- Every transformed word must exist in wordList.
Example
Input
beginWord = "hit"endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
Output
5 Explanation
hit↓
hot
↓
dot
↓
dog
↓
cog
Length = 5
Key Observation
Each word can be treated as a graph node.
Two words are connected if they differ by exactly one character.
Since every transformation has equal cost, BFS gives the shortest path.
Algorithm
- Store words in a set.
- Push beginWord into queue.
- Start BFS traversal.
- Generate all possible one-letter transformations.
- If transformation exists in set, push into queue.
- Continue until endWord is found.
- Return shortest length.
Dry Run
Initial Queue
[hit]
Level 1
hit → hot
Level 2
hot → dot, lot
Level 3
dot → dog
lot → log
lot → log
Level 4
dog → cog
Answer
5Approach : BFS
Start from beginWord and explore all valid transformations level by level.
Since BFS explores shortest paths first, the first time we reach endWord gives the answer.