752. Open the Lock #172
-
Topics: You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: The lock initially starts at You are given a list of Given a Example 1: Input: deadends = ["0201","0101","0102","1212","2002"], target = "0202"
Example 2: Input: deadends = ["8888"], target = "0009" Example 3: Input: deadends = ["8887","8889","8878","8898","8788","8988","7888","9888"], target = "8888" Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We can use Breadth-First Search (BFS) to find the shortest path from the initial state Key Concepts:
Steps:
Let's implement this solution in PHP: 752. Open the Lock <?php
/**
* @param String[] $deadends
* @param String $target
* @return Integer
*/
function openLock($deadends, $target) {
// Convert deadends to a set for O(1) lookup
$dead = array_flip($deadends);
// Check if the initial state '0000' is a deadend
if (isset($dead['0000'])) {
return -1;
}
// Initialize BFS
$queue = [['0000', 0]]; // Queue will store the state and the number of moves to reach it
$visited = ['0000' => true]; // Mark '0000' as visited
// BFS loop
while (!empty($queue)) {
list($state, $moves) = array_shift($queue);
// If we reach the target, return the number of moves
if ($state == $target) {
return $moves;
}
// Get all possible next states
$nextStates = getNextStates($state);
foreach ($nextStates as $next) {
// If this state is not a deadend and has not been visited before
if (!isset($dead[$next]) && !isset($visited[$next])) {
// Mark it as visited and add to the queue
$visited[$next] = true;
$queue[] = [$next, $moves + 1];
}
}
}
// If we exhaust all possibilities and don't reach the target, return -1
return -1;
}
/**
* Helper function to get the next possible states
*
* @param $current
* @return array
*/
function getNextStates($current) {
$result = [];
for ($i = 0; $i < 4; $i++) {
$digit = $current[$i];
// Moving one up
$up = $current;
$up[$i] = ($digit == '9') ? '0' : chr(ord($digit) + 1);
$result[] = $up;
// Moving one down
$down = $current;
$down[$i] = ($digit == '0') ? '9' : chr(ord($digit) - 1);
$result[] = $down;
}
return $result;
}
// Test cases
echo openLock(["0201","0101","0102","1212","2002"], "0202") . "\n"; // Output: 6
echo openLock(["8888"], "0009") . "\n"; // Output: 1
echo openLock(["8887","8889","8878","8898","8788","8988","7888","9888"], "8888") . "\n"; // Output: -1
?> Explanation:
Time Complexity:
Example Walkthrough:
|
Beta Was this translation helpful? Give feedback.
We can use Breadth-First Search (BFS) to find the shortest path from the initial state
'0000'
to thetarget
while avoiding the deadends.Key Concepts:
Graph Representation:
'0000'
,'1234'
) is a node.BFS Approach:
'0000'
and try all possible moves.target
, we return the number of moves (the depth of BFS).