|
| 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