作者:
pandix (麵包屌)
2022-11-02 15:12:54433. Minimum Genetic Mutation
龍大體內的基因突變了。給你開始和目標基因以及合法基因,問突變至目標基因要花幾步
基因是長度為8 由"ACGT"組成的字串
基因突變:改變基因中的一個字元 ex: "AACCGGTT" -> "AACCGGTA"
過程中只能突變至合法基因中有的基因
Example 1:
Input: start = "AACCGGTT", end = "AACCGGTA", bank = ["AACCGGTA"]
Output: 1
Example 2:
Input: start = "AACCGGTT", end = "AAACGGTA", bank =
["AACCGGTA","AACCGCTA","AAACGGTA"]
Output: 2
Example 3:
Input: start = "AAAAACCC", end = "AACCCCCC", bank =
["AAAACCCC","AAACCCCC","AACCCCCC"]
Output: 3
思路:
1.總之先建 set 存那些合法基因,因為問最短步數所以就用BFS
每輪檢查目前走到的基因中有哪些突變後的結果在合法基因中
有就加進下一輪要檢查的基因
2.走到之後可以直接把他移出合法基因代表他已經走過了不用再走了
可以省下一般 BFS 中要用的 visited
3.
Python code:
class Solution:
def minMutation(self, start: str, end: str, bank: List[str]) -> int:
bankset = set(bank)
currstep, nextstep = [start], []
step = 0
while currstep:
for gene in currstep:
if gene == end:
return step
for i in range(8):
for c in 'ACGT':
newgene = gene[:i] + c + gene[i+1:]
if newgene in bankset:
nextstep.append(newgene)
bankset.remove(newgene)
currstep, nextstep = nextstep, []
step += 1
return -1