프로그래밍/알고리즘 풀이
[node.js] 스도쿠 ( 백준 2580번 )
카카수(kakasoo)
2021. 8. 4. 16:50
반응형
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const input = [];
rl.on("line", (line) => {
input.push(line);
}).on("close", () => {
const map = input.map((row) => row.split(" "));
const nullPoint = [];
for (let i = 0; i < map.length; i++) {
for (let j = 0; j < map[i].length; j++) {
if (map[i][j] == 0) {
nullPoint.push([i, j]);
}
}
}
const getSquarePoint = (pos) => parseInt(pos / 3) * 3;
const check = (y, x) => {
for (let i = 0; i < 9; i++) {
if (i === y) continue;
if (map[i][x] == 0) continue;
if (map[i][x] == map[y][x]) {
return false;
}
}
for (let i = 0; i < 9; i++) {
if (i == x) continue;
if (map[y][i] == 0) continue;
if (map[y][i] == map[y][x]) {
return false;
}
}
const squareX = getSquarePoint(x);
const squareY = getSquarePoint(y);
for (let i = squareY; i < squareY + 3; i++) {
for (let j = squareX; j < squareX + 3; j++) {
if (i == y && j == x) continue;
if (map[i][j] == 0) continue;
if (map[i][j] == map[y][x]) {
return false;
}
}
}
return true;
};
const backTracking = (cur) => {
if (cur === nullPoint.length) {
map.forEach((el) => {
console.log(el.join(" "));
});
process.exit();
} else {
const [y, x] = nullPoint[cur];
for (let i = 1; i <= 9; i++) {
map[y][x] = i;
if (check(y, x)) {
backTracking(cur + 1);
}
map[y][x] = 0;
}
}
};
backTracking(0);
});
스도쿠를 풀었다.
x축 봐야 하고 y축 봐야 하고 3 x 3의 정사각형도 봐야 하니깐, 계속 오타나 실수가 나왔다.
일단 0인 지점을 모두 배열에 담아두고,
그 배열에 대한 백트래킹을 진행하였다.
0의 개수만큼 모두 메꾸는 데에 성공했다면 출력하고 종료시켰다.
반응형