433. Minimum Genetic Mutation
BFS, Hash Table, String, AMateList ·Problem Statement
link: LeetCode.cn LeetCode A gene string can be represented by an 8-character long string, with choices from ‘A’, ‘C’, ‘G’, and ‘T’.
Suppose we need to investigate a mutation from a gene string startGene to a gene string endGene where one mutation is defined as one single character changed in the gene string.
For example, “AACCGGTT” –> “AACCGGTA” is one mutation. There is also a gene bank bank that records all the valid gene mutations. A gene must be in bank to make it a valid gene string.
Given the two gene strings startGene and endGene and the gene bank bank, return the minimum number of mutations needed to mutate from startGene to endGene. If there is no such a mutation, return -1.
Note that the starting point is assumed to be valid, so it might not be included in the bank.
Example:
Input: startGene = "AACCGGTT", endGene = "AACCGGTA", bank = ["AACCGGTA"]
Output: 1
Input: startGene = "AACCGGTT", endGene = "AAACGGTA", bank = ["AACCGGTA","AACCGCTA","AAACGGTA"]
Output: 2
Solution Approach
The solution uses Breadth-First Search (BFS) to explore all valid one-step mutations iteratively to find the minimum mutations required to transform the start gene to the end gene.
Algorithm
- Use Breadth-First Search (BFS) to explore all possible one-step mutations from the start gene.
- Ensure each mutation is valid by checking its presence in the gene bank.
- Track visited mutations to avoid redundant processing and return the number of steps when the end gene is reached.
Implement
class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
bank_set = set(bank)
if end not in bank_set:
return -1
queue = deque([start])
visited = set()
choices = ['A', 'C', 'G', 'T']
step = 0
while queue:
size = len(queue)
for _ in range(size):
curr = queue.popleft()
for m in range(8):
for c in choices:
next_seq = curr[:m] + c + curr[m + 1:]
if next_seq == end:
return step + 1
if next_seq in bank_set and next_seq not in visited:
queue.append(next_seq)
visited.add(next_seq)
step += 1
return -1