g0401_0500.s0433_minimum_genetic_mutation.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java Show documentation
Show all versions of leetcode-in-java Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0401_0500.s0433_minimum_genetic_mutation;
// #Medium #String #Hash_Table #Breadth_First_Search
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
@SuppressWarnings("java:S3012")
public class Solution {
private List isInBank(Set set, String cur) {
List res = new ArrayList<>();
for (String each : set) {
int diff = 0;
for (int i = 0; i < each.length(); i++) {
if (each.charAt(i) != cur.charAt(i)) {
diff++;
if (diff > 1) {
break;
}
}
}
if (diff == 1) {
res.add(each);
}
}
return res;
}
public int minMutation(String start, String end, String[] bank) {
Set set = new HashSet<>();
for (String s : bank) {
set.add(s);
}
Queue queue = new LinkedList<>();
queue.offer(start);
int step = 0;
while (!queue.isEmpty()) {
int curSize = queue.size();
while (curSize-- > 0) {
String cur = queue.poll();
if (cur.equals(end)) {
return step;
}
for (String next : isInBank(set, cur)) {
queue.offer(next);
set.remove(next);
}
}
step++;
}
return -1;
}
}