-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_433.java
56 lines (53 loc) · 1.68 KB
/
_433.java
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
package com.fishercoder.solutions.firstthousand;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
public class _433 {
public static class Solution1 {
/*
* My completely original solution, BFS.
*/
public int minMutation(String startGene, String endGene, String[] bank) {
boolean found = false;
for (String b : bank) {
if (b.equals(endGene)) {
found = true;
}
}
if (!found) {
return -1;
}
Queue<String> q = new LinkedList<>();
q.offer(startGene);
int mutations = 0;
Set<String> used = new HashSet<>();
used.add(startGene);
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
String curr = q.poll();
if (curr.equals(endGene)) {
return mutations;
}
for (String candidate : bank) {
if (oneDiff(curr, candidate) && used.add(candidate)) {
q.offer(candidate);
}
}
}
mutations++;
}
return -1;
}
private boolean oneDiff(String word1, String word2) {
int diffChars = 0;
for (int i = 0; i < word1.length(); i++) {
if (word1.charAt(i) != word2.charAt(i)) {
diffChars++;
}
}
return diffChars == 1;
}
}
}