-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy path433.Minimum-Genetic-Mutation.py
51 lines (43 loc) · 1.3 KB
/
433.Minimum-Genetic-Mutation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# https://leetcode.com/problems/minimum-genetic-mutation/description/
#
# algorithms
# Medium (36.58%)
# Total Accepted: 17.1k
# Total Submissions: 47.3k
from collections import deque
class Solution(object):
def minMutation(self, start, end, bank):
"""
:type start: str
:type end: str
:type bank: List[str]
:rtype: int
"""
hash_map = {}
for gene in bank:
hash_map[gene] = True
if end not in hash_map:
return -1
queue = deque([start, '#'])
mutation = 0
genes = ['A', 'C', 'G', 'T']
while True:
head = queue[0]
queue.popleft()
if head == '#':
if len(queue) == 0:
break
queue.append('#')
mutation += 1
else:
for i in xrange(len(head)):
for g in genes:
tmp = head[:i] + g + head[i + 1:]
if head == tmp:
continue
if tmp == end:
return mutation + 1
if hash_map.get(tmp, False):
queue.append(tmp)
hash_map[tmp] = False
return -1