-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path433.minimum-genetic-mutation.java
More file actions
55 lines (46 loc) · 1.66 KB
/
433.minimum-genetic-mutation.java
File metadata and controls
55 lines (46 loc) · 1.66 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
/*
* @lc app=leetcode id=433 lang=java
*
* [433] Minimum Genetic Mutation
*/
// @lc code=start
class Solution {
public int minMutation(String start, String end, String[] bank) {
if (start.equals(end)) return 0;
Set<String> bankSet = new HashSet<>();
Set<String> visited = new HashSet<>();
int count = 0;
for (String s : bank) bankSet.add(s);
char[] keySet = new char[]{'A', 'C', 'G', 'T'};
Queue<String> queue = new LinkedList<>();
queue.add(start);
visited.add(start);
while (!queue.isEmpty()) {
int size = queue.size();
//Level traverse depend on queue size
for (int i = 0; i < size; i++) {
String curr = queue.poll();
if (curr.equals(end)) return count;
//traverse all the character
char[] geneArr = curr.toCharArray();
for (int j = 0; j < geneArr.length; j++) {
char temp = geneArr[j];
//traverse all the possible key
for (char key : keySet) {
geneArr[j] = key;
String newMut = new String(geneArr);
//judge and drill down
if (!visited.contains(newMut) && bankSet.contains(newMut)) {
queue.add(newMut);
visited.add(newMut);
}
}
geneArr[j] = temp;
}
}
count++;
}
return -1;
}
}
// @lc code=end