LeetCode Word Ladder BFS(golang & java)

Problem
在这里插入图片描述
Analysis Process
1.Preprocess the given wordList to find all the universal states and record the universal states in the dictionary, the key is the universal state, and the value is all the words with the universal state
universal state:Replace a letter in a word with *
2.Put tuples that have beginWord and 1 in the queue,1 represents the hierarchy of nodes and we need to return the hierarchy of endWord which is the shortest distance from beginWord
3.To prevent rings, access array records are used
4.When there are elements in the queue, the first element is fetched and recorded as Current Word
5.Find all common states of Current Word, and check whether these common states have mappings for other words, which is done by checking all Combo dict
6.All the words obtained in All Combo dict have a common state with Current Word, so they are connected to Current Word, so they are added to the queue
7.For all newly acquired words, add elements to the queue (word, level + 1) where level is the hierarchy of Current Word
8.Finally, when you reach the desired word, the corresponding level is the length of the shortest transformation sequence

Code
golang

// BFS Time Complexity: O(n*26^l), l = len(word), n=|wordList| Space Complexity: O(n)
func ladderLength(beginWord string, endWord string, wordList []string) int {
    dict := make(map[string]bool) // Put word in the dictionary
    for _, word := range wordList {
        dict[word] = true // use a dictionary to quickly add, remove, and find words
    }
    if _, ok := dict[endWord]; !ok {
        return 0
    }
    // queue := []string{beginWord} Define secondary queues
    var queue []string
    queue = append(queue, beginWord)

    l := len(beginWord)
    steps := 0

    for len(queue) > 0 {
        steps++
        size := len(queue)
        for i := size; i > 0; i-- { // Current level node
            s := queue[0] // The original word
            queue = queue[1:]
            chs := []rune(s)
            for i := 0; i < l; i++ { // Modify each bit of the word
                ch := chs[i]                  // the current word
                for c := 'a'; c <= 'z'; c++ { // a-z
                    if c == ch { // Skip over itself like hot and change it to hot
                        continue
                    }
                    chs[i] = c
                    t := string(chs)
                    if t == endWord { // find the result
                        return steps + 1
                    }
                    if _, ok := dict[t]; !ok { // Not in dict. Skip it
                        continue
                    }
                    delete(dict, t)          // Remove the word from the dictionary, because it has already been accessed, and the repeated access path must not be the shortest
                    queue = append(queue, t) // Add the new word to the queue
                }
                chs[i] = ch // Reset the i-th bit of the word, then do the following
            }
        }
    }
    return 0
}

java

class Solution {
  public int ladderLength(String beginWord, String endWord, List<String> wordList) {

    // Since all words are of same length.
    int L = beginWord.length();

    // Dictionary to hold combination of words that can be formed,
    // from any given word. By changing one letter at a time.
    Map<String, List<String>> allComboDict = new HashMap<>();

    wordList.forEach(
        word -> {
          for (int i = 0; i < L; i++) {
            // Key is the generic word
            // Value is a list of words which have the same intermediate generic word.
            String newWord = word.substring(0, i) + '*' + word.substring(i + 1, L);
            List<String> transformations = allComboDict.getOrDefault(newWord, new ArrayList<>());
            transformations.add(word);
            allComboDict.put(newWord, transformations);
          }
        });

    // Queue for BFS
    Queue<Pair<String, Integer>> Q = new LinkedList<>();
    Q.add(new Pair(beginWord, 1));

    // Visited to make sure we don't repeat processing same word.
    Map<String, Boolean> visited = new HashMap<>();
    visited.put(beginWord, true);

    while (!Q.isEmpty()) {
      Pair<String, Integer> node = Q.remove();
      String word = node.getKey();
      int level = node.getValue();
      for (int i = 0; i < L; i++) {

        // Intermediate words for current word
        String newWord = word.substring(0, i) + '*' + word.substring(i + 1, L);

        // Next states are all the words which share the same intermediate state.
        for (String adjacentWord : allComboDict.getOrDefault(newWord, new ArrayList<>())) {
          // If at any point if we find what we are looking for
          // i.e. the end word - we can return with the answer.
          if (adjacentWord.equals(endWord)) {
            return level + 1;
          }
          // Otherwise, add it to the BFS Queue. Also mark it visited
          if (!visited.containsKey(adjacentWord)) {
            visited.put(adjacentWord, true);
            Q.add(new Pair(adjacentWord, level + 1));
          }
        }
      }
    }

    return 0;
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值