The Word Ladder problem is a classic algorithmic challenge that involves transforming one word into another by changing one letter at a time, ensuring that each intermediate word exists in a given dictionary. This problem is not only a staple in computer science education but also has practical applications in areas like natural language processing and genetic research.
Problem Statement
Given two words, beginWord
and endWord
, and a dictionary wordList
, find the length of the shortest transformation sequence from beginWord
to endWord
, such that:
- Only one letter can be changed at a time.
- Each transformed word must exist in the word list.
Return 0 if no such transformation sequence exists.
Program Structure
The Go program to solve the Word Ladder problem using Breadth-First Search (BFS) is structured as follows:
- Graph Representation: The problem is modeled as a graph where each word is a node, and edges exist between words that differ by exactly one letter.
- BFS Implementation: BFS is used to traverse the graph level by level, ensuring the shortest path is found.
- Helper Functions: Functions are implemented to check if two words differ by one letter and to generate all possible one-letter transformations of a word.
- Main Function: Demonstrates the usage of the Word Ladder solution with example inputs.
Go Program
package main
import (
"fmt"
"strings"
)
// WordLadder finds the length of the shortest transformation sequence from beginWord to endWord
func WordLadder(beginWord string, endWord string, wordList []string) int {
// Create a set for quick lookup
wordSet := make(map[string]bool)
for _, word := range wordList {
wordSet[word] = true
}
// If endWord is not in wordList, no solution exists
if !wordSet[endWord] {
return 0
}
// Initialize BFS
queue := [][]string{{beginWord}}
visited := make(map[string]bool)
visited[beginWord] = true
for len(queue) > 0 {
// Number of elements in the current level
levelSize := len(queue)
for i := 0; i < levelSize; i++ {
path := queue[0]
queue = queue[1:]
lastWord := path[len(path)-1]
// Generate all possible one-letter transformations
for _, nextWord := range getAdjacentWords(lastWord, wordSet) {
if nextWord == endWord {
return len(path) + 1
}
if !visited[nextWord] {
visited[nextWord] = true
newPath := append([]string{}, path...)
newPath = append(newPath, nextWord)
queue = append(queue, newPath)
}
}
}
}
return 0
}
// getAdjacentWords generates all words in the wordSet that are one letter different from the given word
func getAdjacentWords(word string, wordSet map[string]bool) []string {
var adjacent []string
for i := 0; i < len(word); i++ {
for c := 'a'; c <= 'z'; c++ { if byte(c) == word[i] { continue } newWord := word[:i] + string(c) + word[i+1:] if wordSet[newWord] { adjacent = append(adjacent, newWord) } } } return adjacent } func main() { beginWord := "hit" endWord := "cog" wordList := []string{"hot", "dot", "dog", "lot", "log", "cog"} result := WordLadder(beginWord, endWord, wordList) if result > 0 {
fmt.Printf("The shortest transformation sequence from '%s' to '%s' is of length %d.\n", beginWord, endWord, result)
} else {
fmt.Printf("No transformation sequence exists from '%s' to '%s'.\n", beginWord, endWord)
}
}
Documentation
The Go program provided solves the Word Ladder problem using the BFS algorithm. Below is a detailed explanation of each component of the program:
1. WordLadder Function
The WordLadder
function is the core of the solution. It takes three parameters:
beginWord
: The starting word.endWord
: The target word.wordList
: A slice of valid intermediate words.
The function returns an integer representing the length of the shortest transformation sequence. If no such sequence exists, it returns 0.
Steps:
- Word Set Creation: Converts the
wordList
into a set for O(1) lookup times. - End Word Check: If
endWord
is not in thewordSet
, the function immediately returns 0. - BFS Initialization: Initializes the BFS queue with a slice containing only the
beginWord
. It also initializes avisited
map to keep track of visited words. - BFS Traversal: While the queue is not empty, the function iterates through each level of the BFS tree. For each word at the current level, it generates all possible one-letter transformations that exist in the
wordSet
and haven’t been visited yet. If a transformation equals theendWord
, the function returns the current path length plus one. - No Path Found: If the BFS completes without finding the
endWord
, the function returns 0.
2. getAdjacentWords Function
The getAdjacentWords
function generates all valid one-letter transformations of a given word that exist in the wordSet
.
Steps:
- Iterates through each character position in the word.
- For each position, iterates through all lowercase alphabet letters (‘a’ to ‘z’).
- Generates a new word by replacing the character at the current position with the new letter.
- If the new word exists in the
wordSet
, it is added to the list of adjacent words.
3. main Function
The main
function demonstrates how to use the WordLadder
function. It defines example inputs and prints the result of the transformation sequence length.
How the Program Works
- Initialization: The program starts by initializing the
beginWord
,endWord
, and thewordList
. - Word Set: The
wordList
is converted into a set for efficient lookup. - BFS Queue: The BFS queue is initialized with a path containing only the
beginWord
. - BFS Traversal: The program performs BFS by dequeuing the first path, generating all adjacent words, and enqueuing new paths that include these adjacent words.
- Termination: If the
endWord
is found during traversal, the program returns the length of the path. If the queue is exhausted without finding theendWord
, it returns 0.
Example Output
Given the following inputs:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log","cog"]
The program outputs:
The shortest transformation sequence from 'hit' to 'cog' is of length 5.
The transformation sequence is:
- hit
- hot
- dot
- dog
- cog
Conclusion
The provided Go program efficiently solves the Word Ladder problem using the BFS algorithm. By modeling the problem as a graph and leveraging BFS for traversal, the program ensures that the shortest transformation sequence is found. This approach guarantees optimal performance, especially for large dictionaries, making it a robust solution for related computational challenges.
Excerpt
Discover how to solve the Word Ladder problem using BFS in Go. This comprehensive guide includes detailed explanations and a well-documented Go program example.