λ¬Έμ
νμ΄ κ³Όμ
λ¬Έμμ΄μ κΈ°μ€μΌλ‘ νΉμ μ«μμ λλ¬νκΈ° μν μ΅μ νμ μλ₯Ό ꡬνλ λ¬Έμ μ
λλ€.
κ° μ«μμ λν΄μ μ¦κ°νκ±°λ κ°μν μ μμΌλ©° deadends
μ ν¬ν¨λμ§ μλ μ«μμ λν΄μλ§ νμμ μ§νν©λλ€.
λ°λΌμ 쑰건μ λ§λλ‘ BFS
λ₯Ό μννλ©° λͺ©ν μ«μμ λλ¬νκΈ° μν μ΅μ νμλ₯Ό ꡬνλ©΄ λ©λλ€.
μ½λ
/**
* @param {string[]} deadends
* @param {string} target
* @return {number}
*/
var openLock = function (deadends, target) {
const digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
function bfs(start) {
if (deadends.includes(start)) return -1;
q = [];
visit = new Array(10000).fill(false);
q.push([start, 0]);
visit[+start] = true;
while (q.length) {
const [here, cost] = q.shift();
if (here === target) return cost;
for (let i = 0; i < 4; i++) {
let digit = +here[i];
const prevDigitIdx = digit - 1 < 0 ? 9 : digit - 1;
const nextDigitIdx = (digit + 1) % 9;
const prevDigit = `${digits[prevDigitIdx]}`;
const nextDigit = `${digits[nextDigitIdx]}`;
[prevDigit, nextDigit].forEach((newDigit) => {
const there = here.slice(0, i) + newDigit + here.slice(i + 1);
if (!deadends.includes(there) && !visit[+there]) {
q.push([there, cost + 1]);
visit[+there] = true;
}
});
}
}
return -1;
}
const answer = bfs("0000");
return answer;
};
λ°μν
'π algorithm > leetcode' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
LeetCode 416 - Partition Equal Subset Sum (Medium) (0) | 2021.03.04 |
---|---|
LeetCode 560 - Subarray Sum Equals K (Medium) (2) | 2021.03.04 |
LeetCode 11 - Container With Most Water (Medium) (0) | 2021.03.04 |
LeetCode 763 - Partition Labels (Medium) (0) | 2021.03.04 |
LeetCode 48 - Rotate Image (Medium) (0) | 2021.03.04 |
π¬ λκΈ