Leetcode 127. Word Ladder

本文介绍了一个基于广度优先搜索(BFS)算法的问题解决方案:给定两个单词开始词和目标词,以及一个词典列表,如何找出从开始词到目标词最短的转换序列。文章详细解释了算法的具体实现,并通过示例展示了其应用。

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

Question

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 intermediate word must exist in the word list
For example,

Given:
beginWord = “hit”
endWord = “cog”
wordList = [“hot”,”dot”,”dog”,”lot”,”log”]
As one shortest transformation is “hit” -> “hot” -> “dot” -> “dog” -> “cog”,
return its length 5.

code

/**
     * BFS方式
     *
     * @param start
     * @param end
     * @param dict
     * @return
     */
    public int ladderLength(String start, String end, Set<String> dict) {
        if (start == null || end == null || dict == null) {
            return 0;
        }
        //用于BFS时候使用
        Queue<String> q = new LinkedList<String>();
        q.offer(start);

        //存储已经遍历过的数据,防止重复遍历
        HashSet<String> set = new HashSet<String>();
        set.add(start);

        int level = 1;

        while (!q.isEmpty()) {
            int size = q.size();
            level++;
            for (int i = 0; i < size; i++) {
                String s = q.poll();
                int len = s.length();

                for (int j = 0; j < len; j++) {
                    StringBuilder sb = new StringBuilder(s);
                    for (char c = 'a'; c <= 'z'; c++) {
                        sb.setCharAt(j, c);
                        String tmp = sb.toString();

                        if (tmp.equals(end)) {
                            return level;
                        }
                        if (set.contains(tmp) || !dict.contains(tmp)) {
                            continue;
                        }
                        set.add(tmp);
                        q.offer(tmp);
                    }
                }

            }
        }
        return 0;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值