https://leetcode.com/problems/open-the-lock/description/?envType=daily-question&envId=2024-04-22
function openLock(deadends, target) {
let deadSet = new Set(deadends);
let queue = ["0000"];
let visited = new Set(["0000", ...deadends]);
let turns = 0;
while (queue.length > 0) {
let size = queue.length;
for (let i = 0; i < size; i++) {
let current = queue.shift();
if (current === target) return turns;
if (deadSet.has(current)) continue;
for (let j = 0; j < 4; j++) {
let digit = parseInt(current[j]);
let next1 = current.substring(0, j) + (digit === 9 ? 0 : digit + 1) + current.substring(j + 1);
let next2 = current.substring(0, j) + (digit === 0 ? 9 : digit - 1) + current.substring(j + 1);
if (!visited.has(next1) || !visited.has(next2)) {
queue.push(next1);
visited.add(next1);
queue.push(next2);
visited.add(next2);
}
}
}
turns++;
}
return -1;
}
Top comments (0)