I'm working on a problem from Leetcode where we're given a lock combination to reach from the starting combination of 0000. You can only rotate one lock wheel at a time, and you must do it using as few turns as possible. I have my solution to do this, and it works fine, but I don't know how to actually print out the path that the BFS takes to reach this solution (i.e. the intermediary combinations used to reach it). Any help would be appreciated!
class Solution {
private static final String START = "0000";
public int openLock(String[] deadends, String target) {
if (target == null || target.length() == 0) return -1;
Set<String> visited = new HashSet<>(Arrays.asList(deadends));
Queue<String> queue = new LinkedList<>();
int level = 0;
queue.offer(START);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
String currentLock = queue.poll();
if (!visited.add(currentLock)) continue;
if (currentLock.equals(target)) return level;
for (String nextLock : getNextStates(currentLock)) {
if (!visited.contains(nextLock)) queue.offer(nextLock);
}
}
level++;
}
return -1;
}
private List<String> getNextStates(String lock) {
List<String> locks = new LinkedList<>();
char[] arr = lock.toCharArray();
for (int i = 0; i < arr.length; i++) {
char c = arr[i];
arr[i] = c == '9' ? '0' : (char) (c + ((char) 1));
locks.add(String.valueOf(arr));
arr[i] = c == '0' ? '9' : (char) (c - ((char) 1));
locks.add(String.valueOf(arr));
arr[i] = c;
}
return locks;
}
}