-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinimumGeneticMutation.py
More file actions
59 lines (48 loc) · 1.78 KB
/
MinimumGeneticMutation.py
File metadata and controls
59 lines (48 loc) · 1.78 KB
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
52
53
54
55
56
57
58
59
# Question link - https://leetcode.com/problems/minimum-genetic-mutation/?envType=study-plan-v2&envId=top-interview-150
from typing import List
import collections
class Solution:
# helper function to check if difference is exactly one
def isDiff(self, s1, s2):
if len(s1) != len(s2):
return False
cnt = 0
for i in range(len(s1)):
if s1[i] != s2[i]:
cnt += 1
return cnt == 1
def minMutation(self, startGene: str, endGene: str, bank: List[str]) -> int:
# If endGene is not in bank, it's impossible
if endGene not in bank:
return -1
# Create the adj map using a dictionary instead of a list
adj = {}
# Initialize adjacency lists for all genes
adj[startGene] = []
for gene in bank:
adj[gene] = []
# Connect bank genes to each other
for i in range(len(bank)):
for j in range(i + 1, len(bank)):
if self.isDiff(bank[i], bank[j]):
adj[bank[i]].append(bank[j])
adj[bank[j]].append(bank[i])
# Connect startGene to bank genes
for gene in bank:
if self.isDiff(startGene, gene):
adj[startGene].append(gene)
adj[gene].append(startGene)
# BFS
q = collections.deque()
q.append((startGene, 0))
visited = set()
visited.add(startGene)
while q:
node, level = q.popleft()
if node == endGene:
return level
for nei in adj[node]:
if nei not in visited:
visited.add(nei)
q.append((nei, level + 1))
return -1 # if not found