Leetcode 127. Word Ladder(java)

本文探讨了从一个单词开始,通过字典中的单词逐步转换到目标单词的最短路径问题。使用了BFS和双向BFS算法解决,详细解析了算法思路与实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given two words (beginWord and endWord), and a dictionary’s word list, find the length of shortest transformation sequence from beginWord to endWord, such that:

Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed word.
Note:

Return 0 if there is no such transformation sequence.
All words have the same length.
All words contain only lowercase alphabetic characters.
You may assume no duplicates in the word list.
You may assume beginWord and endWord are non-empty and are not the same.

Example 1:

Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]

Output: 5

Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
Example 2:

Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]

Output: 0

Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.

解法一:BFS,不解释

class Solution {
    //uni-directional BFS
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        int len = 0;
        Set<String> set = new HashSet<>();
        for (int i = 0; i < wordList.size(); i++) {
            set.add(wordList.get(i));
        }
        if (!set.contains(endWord)) return 0;
        Queue<String> q = new LinkedList<>();
        q.offer(beginWord);
        while (!q.isEmpty()) {
            len++;
            int size = q.size(); 
            while (size-- > 0) {
                StringBuilder cur = new StringBuilder(q.poll());
                for (int i = 0; i < cur.length(); i++) {
                    char c = cur.charAt(i);
                    for (int j = 0; j < 26; j++) {
                        if (c == (char)('a' + j)) continue;
                        cur.setCharAt(i, (char)('a' + j));
                        String str = cur.toString();
                        if (set.contains(str)) {
                            if (str.equals(endWord)) {
                                return len + 1;
                            }
                            q.offer(str);
                            set.remove(str);
                        }
                        cur.setCharAt(i, c);
                    }
                }
            }
        }
        return 0;
    }
}

解法二:Bidirectional BFS

这个写法还有点麻烦了,实际上要理解的是,每个方向都只在乎一个前进方向的最前一排node和另一个方向的最前一排node,因此只需要q1, q2和前进的时候新建的q,每次前进一排后交换q和q1, 然后每次前进之前判断q1和q2的大小(如果q1>q2,交换q1和q2),保证每次都用前排数量最小的排前进即可。

class Solution {
    //Bi-directional BFS
    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        HashSet<String> set = new HashSet<>();
        for (int i = 0; i < wordList.size(); i++) {
            set.add(wordList.get(i));
        }
        if (!set.contains(endWord)) return 0;
        HashSet<String> s1 = new HashSet<>();
        HashSet<String> s2 = new HashSet<>();
        List<String> next1 = new ArrayList<>();
        List<String> next2 = new ArrayList<>();
        s2.add(beginWord);
        s1.add(endWord);
        next1.add(endWord);
        next2.add(beginWord);
        int result = 0;
        while (!next2.isEmpty()) {
            result++;
            //swap s1 and s2
            HashSet<String> temp = s1;
            s1 = s2;
            s2 = temp;
            List<String> cur = next1;
            next1 = next2;
            next2 = cur;
            
            int size = next1.size();
            while (--size >= 0) {
                StringBuilder s = new StringBuilder(next1.get(size));
                for (int i = 0; i < s.length(); i++) {
                    char c = s.charAt(i);
                    for (int j = 0; j < 26; j++) {
                        if (c == (char)(j+'a')) continue;
                        s.setCharAt(i, (char)(j+'a'));
                        String str = s.toString();
                        if (s2.contains(str)) {
                            return result + 1;
                        }
                        if (set.contains(str)) {
                            next1.add(str);
                            s1.add(str);
                            set.remove(str);
                        }
                    }
                    s.setCharAt(i, c);
                }
                next1.remove(next1.get(size));
            }
        }
        return 0;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值