A gene string can be represented by an 8-character long string, with choices from "A"
, "C"
, "G"
, "T"
.
Suppose we need to investigate on a mutation (mutation from ' start ' to ' end '), where one mutation is defined as one sin GLE character changed in the gene string.
For example, "AACCGGTT"
is "AACCGGTA"
1 mutation.
Also, there is a given gene "bank", which records all the valid gene mutations. A gene must is in the bank to make it a valid gene string.
Now, given 3 Things-start, end, bank, your task was to determine what's the minimum number of mutations needed to mutate From ' Start ' to ' end '. If There is no such a mutation, return-1.
Note:
- Starting point was assumed to being valid, so it might not being included in the bank.
- If multiple mutations is needed, all mutations during in the sequence must is valid.
- 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
The subject and Leetcode 127. Word ladder--Word solitaire is exactly the same, without any difference, using breadth-first search to find the shortest path. be gratified to write code over and over, direct AC.
Java
classSolution { Public intminmutation (string start, String end, string[] bank) {if(Bank = =NULL|| Bank.length = = 0)return-1; Char[] Gen = {' A ', ' C ', ' G ', ' T '}; HashSet<String> Bankset =NewHashset<>(); for(String S:bank) Bankset.add (s); Queue<String> q =NewLinkedlist<>(); HashMap<string, integer> res =NewHashmap<>(); Res.put (Start,0); Q.add (start); while(!Q.isempty ()) {String s=Q.poll (); Bankset.remove (s); for(inti = 0; I < s.length (); i++) { Char[] Next =S.tochararray (); for(CharC:gen) {Next[i]=C; String nexts=NewString (next); if(Bankset.contains (nexts)) {res.put (nexts, Res.get (s)+ 1); if(Nexts.equals (end))returnRes.get (nexts); Q.add (nexts); } } } } return-1; }}
(Java) Leetcode 433. Minimum genetic mutation--minimal gene change