Golang
Golang

 

 

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:

  1. Word Set Creation: Converts the wordList into a set for O(1) lookup times.
  2. End Word Check: If endWord is not in the wordSet, the function immediately returns 0.
  3. BFS Initialization: Initializes the BFS queue with a slice containing only the beginWord. It also initializes a visited map to keep track of visited words.
  4. 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 the endWord, the function returns the current path length plus one.
  5. 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:

  1. Iterates through each character position in the word.
  2. For each position, iterates through all lowercase alphabet letters (‘a’ to ‘z’).
  3. Generates a new word by replacing the character at the current position with the new letter.
  4. 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

  1. Initialization: The program starts by initializing the beginWord, endWord, and the wordList.
  2. Word Set: The wordList is converted into a set for efficient lookup.
  3. BFS Queue: The BFS queue is initialized with a path containing only the beginWord.
  4. BFS Traversal: The program performs BFS by dequeuing the first path, generating all adjacent words, and enqueuing new paths that include these adjacent words.
  5. Termination: If the endWord is found during traversal, the program returns the length of the path. If the queue is exhausted without finding the endWord, 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:

  1. hit
  2. hot
  3. dot
  4. dog
  5. 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.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)