public int ladderLength(String beginWord, String endWord, Set<String> wordList) {
        if (beginWord == null || endWord == null || wordList == null) return -1;
        Queue<String> q = new LinkedList<String>();
        HashMap<String, Integer> distance = new HashMap<String, Integer>();
        q.add(beginWord);
        distance.put(beginWord, 1);
        while (!q.isEmpty()) {
            String word = q.remove();
            for (String next : expand(word, wordList)) {
                if (!distance.containsKey(next)) {
                    distance.put(next, distance.get(word) + 1);
                    q.add(next);
                }
            }
        }
        return distance.containsKey(endWord) ? distance.get(endWord) : 0;
    }