Word Ladder

Given two words (start and end), and a dictionary, find the length of shortest transformation sequence from start to end, such that: Only one letter can be changed at a time Each intermediate word must exist in the dictionary.

  • Time: O(n)
  • Space: O(1)
class Node {
    String word;
    int level;
    public Node(String w, int l) {
        word = w;
        level = l;
    }
}
public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
    Queue<Node> queue = new LinkedList<>();
    queue.offer(new Node(beginWord, 1));
    while (!queue.isEmpty()) {
        Node curNode = queue.poll();
        if (curNode.word.equals(endWord)) {
            return curNode.level;
        }
        for (int i = 0; i < curNode.word.length(); i++) {
            char[] chars = curNode.word.toCharArray();
            for (char c = 'a'; c <= 'z'; c++) {
                chars[i] = c;
                String newWord = new String(chars);
                if (wordList.contains(newWord)) {
                    queue.offer(new Node(newWord, curNode.level + 1));
                    wordList.remove(newWord);
                }
            }
        }
    }
    return 0;
}

results matching ""

    No results matching ""