Woodyiiiiiii / LeetCode

My private record of Leetcode solution

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Leetcode 433. Minimum Genetic Mutation

Woodyiiiiiii opened this issue · comments

BFS + 回溯法

Tips:

  1. 注意要恰当地移除gene库里面的字符串,否则会造成死循环。移除的后果是其他本来可以mutate到这个字符串的字符串没机会了,但没区别,因为已经有字符串达到了
class Solution {
    public int minMutation(String startGene, String endGene, String[] bank) {
        Set<String> bankSet = new HashSet<>(Arrays.asList(bank));
        if (!bankSet.contains(endGene)) {
            return -1;
        }
        
        char[] genes = new char[]{'A', 'C', 'G', 'T'};
        Queue<String> queue = new LinkedList<>();
        queue.offer(startGene);
        int level = 0;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                String gene = queue.poll();
                if (gene.equals(endGene)) {
                    return level;
                }
                char[] geneChars = gene.toCharArray();
                for (int j = 0; j < geneChars.length; j++) {
                    char oldChar = geneChars[j];
                    for (char c : genes) {
                        geneChars[j] = c;
                        String newGene = new String(geneChars);
                        if (bankSet.contains(newGene)) {
                            queue.offer(newGene);
                            bankSet.remove(newGene);
                        }
                    }
                    geneChars[j] = oldChar;
                }
            }
            level++;
        }
        return -1;
    }
}