Skip to content

Commit

Permalink
#19 23.02.13 > 4 > N-queen
Browse files Browse the repository at this point in the history
  • Loading branch information
beurmuz committed Feb 13, 2023
1 parent eee5e90 commit b5a184e
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
40 changes: 40 additions & 0 deletions src/bj/gold/4/9663.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"use strict";

/**
* N-Queen 문제는 크기가 N*N인 체스판 위에 퀸 N개를 서로 공격할 수 없게 놓는 문제이다.
* - 서로 공격할 수 없다? => 퀸의 일직선 및 대각선 상에는 아무것도 놓이면 안된다는 말과 같다.
* - cf.[9663](https://velog.io/@jxlhe46/%EB%B0%B1%EC%A4%80-9663%EB%B2%88.-N-Queen)
* - cf.[9663_2](https://gobae.tistory.com/57)
*/
const n = require("fs").readFileSync("/dev/stdin").toString();

const solution = (n) => {
let answer = 0;
let row = Array.from({ length: n + 1 }, () => 0);

const isPossible = (L) => {
for (let i = 0; i < L; i++) {
if (row[L] === row[i] || L - i === Math.abs(row[L] - row[i]))
return false;
}
return true;
};

const dfs = (L) => {
if (L === n) {
answer++;
return;
} else {
for (let i = 0; i < n; i++) {
row[L] = i;
if (isPossible(L)) {
dfs(L + 1);
}
}
}
};
dfs(0);
return answer;
};

console.log(solution(+n));
1 change: 1 addition & 0 deletions src/bj/gold/4/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@
| :-: | :------: | :----------------------: | :-------: | :-------: | :---------------------------: |
| 1 | 14502 | [연구소](./14502.js) | 23.02.03 | X | [23.02.06](./replay/14502.js) |
| 2 | 14500 | [테트로미노](./14500.js) | 23.02.06 | X |
| 3 | 9663 | [N-Queen](./9663.js) | 23.02.13 | X |

0 comments on commit b5a184e

Please sign in to comment.