A JAVA solution to updated problem


  • 1
    D
    public class Solution {
        public int ladderLength(String beginWord, String endWord, List<String> wordList) {
            Queue<String> queue = new LinkedList<>();
            Map<String,Integer> map = new HashMap<>();
            queue.offer(beginWord);
            map.put(beginWord, 1);
            while (!queue.isEmpty()) {
                String word = queue.poll();
                int dis = map.get(word);
                for (String str : wordList) {
                    if (!map.containsKey(str)) {
                        int index = 0;
                        int diff = 0;
                        while (index < str.length()) {
                            if (word.charAt(index) != str.charAt(index)) {
                                diff++;
                                if (diff > 1) {
                                    break;
                                }
                            }
                            index++;
                        }
                        if (diff == 1) {
                            if (str.equals(endWord)) {
                                return dis + 1;
                            }
                            queue.offer(str);
                            map.put(str, dis + 1);
                        }
                    }
    
                }
            }
            return 0;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.