LeetCode 752: Open the Lock Solution
Master LeetCode problem 752 (Open the Lock), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
752. Open the Lock
Problem Explanation
Explanation:
To solve this problem, we can use a breadth-first search (BFS) approach. We start from the initial state '0000' and explore all possible combinations by rotating each wheel in both directions. We keep track of the visited states to avoid revisiting them. If we reach the target state, we return the number of steps taken. If it's not possible to reach the target state, we return -1.
Algorithm:
- Initialize a queue with the initial state '0000' and a set to store visited states.
- While the queue is not empty:
- Pop the current state from the queue.
- Check if it is the target state, return the number of steps taken.
- If it is a deadend or already visited state, skip to the next state.
- Rotate each wheel in both directions and add the new states to the queue if they are valid.
- If the target state is not reached, return -1.
Time Complexity:
The time complexity of this approach is O(10000) as there are 10000 possible states (10 * 10 * 10 * 10).
Space Complexity:
The space complexity is O(10000) for storing the visited states and O(n) for the queue.
:
Solution Code
class Solution {
public int openLock(String[] deadends, String target) {
Set<String> deads = new HashSet<>(Arrays.asList(deadends));
Set<String> visited = new HashSet<>();
Queue<String> queue = new LinkedList<>();
queue.offer("0000");
visited.add("0000");
int steps = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
String current = queue.poll();
if (deads.contains(current)) {
continue;
}
if (current.equals(target)) {
return steps;
}
for (int j = 0; j < 4; j++) {
for (int k = -1; k <= 1; k += 2) {
char[] chars = current.toCharArray();
chars[j] = (char)(((chars[j] - '0' + k + 10) % 10) + '0');
String next = new String(chars);
if (!visited.contains(next)) {
visited.add(next);
queue.offer(next);
}
}
}
}
steps++;
}
return -1;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 752 (Open the Lock)?
This page provides optimized solutions for LeetCode problem 752 (Open the Lock) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 752 (Open the Lock)?
The time complexity for LeetCode 752 (Open the Lock) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 752 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 752 in Java, C++, or Python.