Leetcode 752: Open the Lock

grid47
grid47
Exploring patterns and algorithms
Aug 23, 2024 7 min read

A lock with combination digits, where each correct digit softly glows as it’s guessed correctly.
Solution to LeetCode 752: Open the Lock Problem

You are given a lock with 4 rotating wheels, each containing 10 slots labeled ‘0’ to ‘9’. The wheels can rotate freely and wrap around. You must determine the minimum number of moves required to reach a target lock configuration, avoiding certain deadends.
Problem
Approach
Steps
Complexity
Input: The input consists of a list of deadends and a target string, representing the lock's target configuration.
Example: deadends = ['0201', '0101', '0102', '1212', '2002'], target = '0202'
Constraints:
• 1 <= deadends.length <= 500
• deadends[i].length == 4
• target.length == 4
• target will not be in the list of deadends
• target and deadends[i] consist of digits only
Output: Return the minimum number of turns required to reach the target configuration, or -1 if it is impossible.
Example: For deadends = ['0201', '0101', '0102', '1212', '2002'] and target = '0202', the output is 6.
Constraints:
Goal: To find the shortest path from '0000' to the target configuration, avoiding deadends.
Steps:
• Use a breadth-first search (BFS) starting from '0000'.
• At each step, generate all possible valid configurations by rotating one of the wheels.
• If the generated configuration is a deadend, skip it.
• If the configuration matches the target, return the number of moves taken to reach it.
Goal: The input guarantees that the target is not part of the deadends list.
Steps:
• The list of deadends will contain between 1 and 500 elements.
• The length of each deadend string is exactly 4 characters.
• The target string has a length of 4 characters.
Assumptions:
• The input deadends and target strings consist only of digits between '0' and '9'.
• The target configuration is not present in the list of deadends.
Input: deadends = ['0201', '0101', '0102', '1212', '2002'], target = '0202'
Explanation: Starting from '0000', the sequence '0000' -> '1000' -> '1100' -> '1200' -> '1201' -> '1202' -> '0202' leads to the target, taking 6 moves.

Input: deadends = ['8888'], target = '0009'
Explanation: Starting from '0000', the sequence '0000' -> '0009' requires just 1 move.

Input: deadends = ['8887', '8889', '8878', '8898', '8788', '8988', '7888', '9888'], target = '8888'
Explanation: It is impossible to reach the target without hitting a deadend.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus