Word Ladder 0 - Is a ladder there
Problem
Change a word into another by changing only only one character at a time. All intermediate words should be contained in a dictionary.
Examples
Example 1:
Input:
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output:
true
Explanation: One shortest transformation sequence is "hit" -> "hot" -> "dot" -> "dog" -> "cog"
Solution
This problem is pretty simple if we can choose a proper data structure. Here is the second part of the problem - [Word Ladder 1 - Get Ladder Length](word-ladder-1-get-ladder-length).
Method 1 - BFS
Example
Given a dictionary {"DOG", "COT", "COG", "FOG", "DOT"}, start word "FOG", and target word "COT".
From "FOG", we can generate new words by changing each letter to any other letter from 'A' to 'Z', but only keep those present in the dictionary. Here, "COG" and "DOG" are valid next steps.
If any transformed word matches the target, we've succeeded. Otherwise, we repeat the process for each valid transformation. If no sequence leads to the target, the search fails. For instance, "FOG" → "COG" → "COT" is a valid path.
This problem naturally fits a breadth-first search (BFS) approach, using a queue to explore all possible transformations level by level.
Code
Java
public boolean isNavigable(final String beginWord, final String endWord, final Set<String> dictionary) {
if (beginWord.length() != endWord.length()) {
return false;
}
if (beginWord.equals(endWord)) {
return true;
}
dictionary.remove(beginWord);
final Queue<String> queue = new LinkedList<String>();
queue.add(beginWord);
while (!queue.isEmpty()) {
final String top = queue.remove();
for (int i = 0; i<top.length(); i++) {
char[] temp = top.toCharArray();
for (char j = 'A'; j<'Z'; j++) {
temp[i] = j;
final String candidate = new String(temp);
if (candidate.equals(endWord)) {
System.out.print("-->" + candidate);
return true; } else if (dictionary.contains(candidate)) {
dictionary.remove(candidate);
queue.add(candidate);
System.out.print("-->" + candidate);
}
}
}
}
return false;
}
Complexity
- ⏰ Time complexity:
O(n) - 🧺 Space complexity:
O(n)