Skip to content

Commit db946ab

Browse files
committed
feat: minimum-genetic-mutation
1 parent 205887e commit db946ab

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Diff for: bfs.minimum-genetic-mutation.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from typing import List
2+
3+
class Solution:
4+
"""
5+
433. 最小基因变化
6+
https://leetcode-cn.com/problems/minimum-genetic-mutation/
7+
一条基因序列由一个带有8个字符的字符串表示,其中每个字符都属于 "A", "C", "G", "T"中的任意一个。
8+
假设我们要调查一个基因序列的变化。一次基因变化意味着这个基因序列中的一个字符发生了变化。
9+
例如,基因序列由"AACCGGTT" 变化至 "AACCGGTA" 即发生了一次基因变化。
10+
与此同时,每一次基因变化的结果,都需要是一个合法的基因串,即该结果属于一个基因库。
11+
现在给定3个参数 — start, end, bank,分别代表起始基因序列,目标基因序列及基因库,请找出能够使起始基因序列变化为目标基因序列所需的最少变化次数。如果无法实现目标变化,请返回 -1。
12+
"""
13+
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
14+
possible = ['A', 'C', 'G', 'T']
15+
# 定义初始队列
16+
queue = [(start, 0)]
17+
while queue:
18+
# 定义终止条件
19+
word, step = queue.pop(0)
20+
if word == end:
21+
return step
22+
# 在 bank 中寻找相差一位的
23+
for i in range(len(word)):
24+
for p in possible:
25+
tmp = word[:i] + p + word[i+1:]
26+
if tmp in bank:
27+
bank.remove(tmp)
28+
queue.append((tmp, step + 1))
29+
return -1
30+
31+
32+
so = Solution()
33+
print(so.minMutation("AAAACCCC", 'CCCCCCCC', ["AAAACCCA","AAACCCCA","AACCCCCA","AACCCCCC","ACCCCCCC","CCCCCCCC","AAACCCCC","AACCCCCC"]))

0 commit comments

Comments
 (0)