Problem Description:
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
Problem Solving Ideas:
This problem can be solved with BFS, which is very similar to word ladder.
But there are more restrictions on this problem:
1.gene is selected from {' A ', ' C ', ' G ', ' T '}.
2. The results of each mutation must be found in the bank.
We use a queue to store the current gene string, and another queue to store the number of changes.
These two queues should be kept in sync.
In the first place you can check if end is in the bank, not in the bank, anyway, we can not reach the end point, directly back to 1.
Check whether the current string can join the queue:
1. Have you ever visited
2. Is it possible to find in the bank
Code:
classSolution { Public: intMinmutation (stringStartstringEnd, vector<string>&Bank) {Vector<Char> genes = {'A','T','C','G'}; Unordered_set<string>s (Bank.begin (), Bank.end ()); if(S.count (end) = =0)return-1; Unordered_set<string>visited; Queue<string>Q; Queue<int>distance_q; Q.push (start); Distance_q.push (0); while(!Q.empty ()) { stringCur =Q.front (); Q.pop (); intdis =Distance_q.front (); Distance_q.pop (); for(inti =0; I <8; i++){ for(intj =0; J <4; J + +){ stringtemp =cur; if(Genes[j] = = Temp[i])Continue; Temp[i]=Genes[j]; if(temp = = end)returndis+1; if(Visited.count (temp) = =0&& s.count (temp)! =0) {Visited.insert (temp); Q.push (temp); Distance_q.push (Dis+1); } } } } return-1; }};
433. Minimum Genetic Mutation