다윤 풀이
const filePath = process.platform === "linux" ? "/dev/stdin" : "input.txt"; let N = require("fs").readFileSync(filePath).toString().trim(); N = +N; let count = 0; const board = new Array(15); const promising = (cdx) => { for (let i = 0; i < cdx; i++) { if (board[cdx] == board[i] || cdx - i == Math.abs(board[cdx] - board[i])) { return 0; } } return 1; }; const nqueen = (cdx) => { if (cdx === N) { count++; return; } for (let i = 0; i < N; i++) { board[cdx] = i; if (promising(cdx)) { nqueen(cdx + 1); } } }; nqueen(0); console.log(count);
민수 풀이
let num = Number(require('fs').readFileSync("/dev/stdin").toString().trim()); const chk = (ax, ay, bx, by) => (ax == bx || ay == by || Math.abs((ax - bx) / (ay - by)) == 1); let cnt = 0; const arr = []; function dfs(depth){ if(depth == num){ cnt += 1; return; } for(let i = 0; i < num; i++){ let isChk = true; for(let j = 0; j < arr.length; j++) { if(chk(i, depth, arr[j], j)) isChk = false; } if(isChk){ arr.push(i); dfs(depth + 1); arr.pop(); } } } dfs(0); console.log(cnt);