LeetCode之图的广度优先搜索

433. 最小基因变化

java 复制代码
class Solution {
    public int minMutation(String start, String end, String[] bank) {
        // 将基因库存储在集合中,便于快速查找
        Set<String> bankSet = new HashSet<>(Arrays.asList(bank));
        
        // 如果目标基因不在基因库中,则直接返回 -1
        if (!bankSet.contains(end)) {
            return -1;
        }

        // 定义 BFS 队列
        Queue<String> queue = new LinkedList<>();
        queue.offer(start);

        // 记录变换的步骤
        int steps = 0;

        // 定义基因的四个可变字符
        char[] genes = {'A', 'C', 'G', 'T'};

        // 开始 BFS 遍历
        while (!queue.isEmpty()) {
            int size = queue.size();

            // 处理当前层的所有基因变化
            for (int i = 0; i < size; i++) {
                String currentGene = queue.poll();

                // 如果当前基因是目标基因,返回步骤数
                if (currentGene.equals(end)) {
                    return steps;
                }

                // 生成可能的下一步基因
                for (int j = 0; j < currentGene.length(); j++) {
                    for (char gene : genes) {
                        if (gene != currentGene.charAt(j)) { // 只替换与当前基因不同的字符
                            StringBuilder nextGene = new StringBuilder(currentGene);
                            nextGene.setCharAt(j, gene); // 替换字符
                            String newGene = nextGene.toString();

                            // 如果新生成的基因在库中,加入队列并从银行中移除以避免重复
                            if (bankSet.contains(newGene)) {
                                queue.offer(newGene);
                                bankSet.remove(newGene); // 以避免将来再访问
                            }
                        }
                    }
                }
            }
            steps++; // 每层遍历结束,步数加 1
        }

        return -1; // 如果无法到达目标基因,返回 -1
    }
}
相关推荐
小O的算法实验室4 小时前
IEEE TASE,基于MPC的多无人机协同搜索竞争群体优化方法
算法
Tbisnic4 小时前
BGE-M3 算法详解:从模型架构到三种检索方式的数学原理
算法·自然语言处理·大模型·bert·transformer·注意力机制
Brilliantwxx5 小时前
【算法从零到千】【55-58】哈希位图+常见数学运算 接口
算法
空堂与归6 小时前
用户分群找不到规律?用K-Means聚类算法自动发现数据模式
算法·机器学习·kmeans·聚类
动词ing6 小时前
【C语言】自定义函数+指针入门
c语言·开发语言·算法
重生之后端学习6 小时前
283. 移动零[简单]✅
开发语言·数据结构·算法·leetcode·职场和发展
一只小小的芙厨7 小时前
基础数论总结
笔记·学习·算法
夜不会漫长8 小时前
C++入门(1)
开发语言·c++·算法
wen_zhufeng9 小时前
IndexTTS 2.5 技术报告
人工智能·算法·机器学习
大熊背10 小时前
树莓派相机自动白平衡详解(四)
算法·树莓派·白平衡·isppipeline