433. Minimum Genetic Mutation

A gene string can be represented by an 8-character long string, with choices from "A""C""G""T".

Suppose we need to investigate about a mutation (mutation from "start" to "end"), where ONE mutation is defined as ONE single character changed in the gene string.

For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation.

Also, there is a given gene "bank", which records all the valid gene mutations. A gene must be in the bank to make it a valid gene string.

Now, given 3 things - start, end, bank, your task is to determine what is the minimum number of mutations needed to mutate from "start" to "end". If there is no such a mutation, return -1.

Note:

  1. Starting point is assumed to be valid, so it might not be included in the bank.
  2. If multiple mutations are needed, all mutations during in the sequence must be valid.
  3. You may assume start and end string is not the same.

Example 1:

start: "AACCGGTT"
end:   "AACCGGTA"
bank: ["AACCGGTA"]

return: 1

Example 2:

start: "AACCGGTT"
end:   "AAACGGTA"
bank: ["AACCGGTA", "AACCGCTA", "AAACGGTA"]

return: 2

Example 3:

start: "AAAAACCC"
end:   "AACCCCCC"
bank: ["AAAACCCC", "AAACCCCC", "AACCCCCC"]

return: 3

最小的基因突变所需步数,程序如下所示:

class Solution {
    char[] geneCh = new char[]{'A','T','C','G'};
    public int minMutation(String start, String end, String[] bank) {
        Set<String> reached = new HashSet<>();
        reached.add(start);
        int len = 1;
        Set<String> wordDictSet = new HashSet<>();
        for (String s : bank){
            wordDictSet.add(s);
        }
        while (reached.size() > 0){
            Set<String> tmp = new HashSet<>();
            for (String word : reached){
                int length = word.length();
                for (int i = 0; i < length; ++ i){
                    char ch[] = word.toCharArray();
                    for (char c : geneCh){
                        ch[i] = c;
                        String s = new String(ch);
                        if (wordDictSet.contains(s)){
                            if (s.equals(end)){
                                return len;
                            }
                            wordDictSet.remove(s);
                            tmp.add(s);
                        }
                    }
                }
            }
            if (tmp.size() == 0){
                return -1;
            }
            reached = tmp;
            len ++;
        }
        return -1;        
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值