Skip to content

Leetcode 433. Minimum Genetic Mutation #156

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
Woodyiiiiiii opened this issue Dec 2, 2022 · 0 comments
Open

Leetcode 433. Minimum Genetic Mutation #156

Woodyiiiiiii opened this issue Dec 2, 2022 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

Woodyiiiiiii commented Dec 2, 2022

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;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant