Word Ladder (Shortest Path) in Java: Explanation & Practice
Find shortest transformation sequence
Problem summary
Given beginWord, endWord, and a dictionary, find the length of shortest transformation sequence. Each step changes one letter to form a word in the dictionary.
Starter code
public class Main {
public static void main(String[] args) {
String beginWord = "hit";
String endWord = "cog";
String[] wordList = {"hot","dot","dog","lot","log","cog"};
// BFS from beginWord
// Generate all possible one-letter changes
// Check if in dictionary
// Print: Length: 5
}
}Expected output and test cases
- hit→hot→dot→dog→cog
Length: 5
- endWord not in list
Length: 0
- Direct transformation possible
Length: 2
Hints
- BFS gives shortest path in unweighted graph
- Each word is a node, edges connect words differing by one letter
- Use HashSet for O(1) dictionary lookup
- Remove words from set once visited to avoid cycles
Related Data Structures & Algorithms exercises
- Practice Clone Graph in Java
- Practice Course Schedule (Cycle Detection) in Java
- Practice Rotting Oranges (Multi-source BFS) in Java
Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler