public int ladderLength2(String beginWord, String endWord, Set<String> wordList) {
        if (beginWord == null || endWord == null || wordList == null) return -1;
        Queue<String> q = new LinkedList<String>();
        Set<String> visited = new HashSet<String>();
        q.add(beginWord);
        visited.add(beginWord);
        int length = 0;
        while (!q.isEmpty()) {
            ++length;
            final int SIZE = q.size();
            for (int i = 0; i < SIZE; ++i) {
                String word = q.remove();
                if (word.equals(endWord)) {
                    return length;
                }
                for (String next : expand(word, wordList)) {
                    if (!visited.contains(next)) {
                        visited.add(next);
                        q.add(next);
                    }
                }
            }
        }
        return 0;
    }