Skip to content

Commit c647ff6

Browse files
committed
Add solution #752
1 parent 9404b65 commit c647ff6

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -570,6 +570,7 @@
570570
747|[Largest Number At Least Twice of Others](./0747-largest-number-at-least-twice-of-others.js)|Easy|
571571
748|[Shortest Completing Word](./0748-shortest-completing-word.js)|Easy|
572572
749|[Contain Virus](./0749-contain-virus.js)|Hard|
573+
752|[Open the Lock](./0752-open-the-lock.js)|Medium|
573574
762|[Prime Number of Set Bits in Binary Representation](./0762-prime-number-of-set-bits-in-binary-representation.js)|Easy|
574575
763|[Partition Labels](./0763-partition-labels.js)|Medium|
575576
783|[Minimum Distance Between BST Nodes](./0783-minimum-distance-between-bst-nodes.js)|Easy|

solutions/0752-open-the-lock.js

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
* 752. Open the Lock
3+
* https://leetcode.com/problems/open-the-lock/
4+
* Difficulty: Medium
5+
*
6+
* You have a lock in front of you with 4 circular wheels. Each wheel has 10 slots: '0', '1', '2',
7+
* '3', '4', '5', '6', '7', '8', '9'. The wheels can rotate freely and wrap around: for example
8+
* we can turn '9' to be '0', or '0' to be '9'. Each move consists of turning one wheel one slot.
9+
*
10+
* The lock initially starts at '0000', a string representing the state of the 4 wheels.
11+
*
12+
* You are given a list of deadends dead ends, meaning if the lock displays any of these codes,
13+
* the wheels of the lock will stop turning and you will be unable to open it.
14+
*
15+
* Given a target representing the value of the wheels that will unlock the lock, return the
16+
* minimum total number of turns required to open the lock, or -1 if it is impossible.
17+
*/
18+
19+
/**
20+
* @param {string[]} deadends
21+
* @param {string} target
22+
* @return {number}
23+
*/
24+
var openLock = function(deadends, target) {
25+
const dead = new Set(deadends);
26+
const queue = [['0000', 0]];
27+
const seen = new Set(['0000']);
28+
29+
if (dead.has('0000')) return -1;
30+
while (queue.length) {
31+
const [combo, turns] = queue.shift();
32+
if (combo === target) return turns;
33+
34+
for (let i = 0; i < 4; i++) {
35+
const current = combo[i];
36+
const up = (parseInt(current) + 1) % 10;
37+
const down = (parseInt(current) + 9) % 10;
38+
39+
const nextUp = combo.slice(0, i) + up + combo.slice(i + 1);
40+
if (!seen.has(nextUp) && !dead.has(nextUp)) {
41+
queue.push([nextUp, turns + 1]);
42+
seen.add(nextUp);
43+
}
44+
45+
const nextDown = combo.slice(0, i) + down + combo.slice(i + 1);
46+
if (!seen.has(nextDown) && !dead.has(nextDown)) {
47+
queue.push([nextDown, turns + 1]);
48+
seen.add(nextDown);
49+
}
50+
}
51+
}
52+
53+
return -1;
54+
};

0 commit comments

Comments
 (0)