Skip to content

Commit bf4ed56

Browse files
committed
add: ๋ฐฑ์ค€/N-Queen
1 parent 89995bd commit bf4ed56

1 file changed

Lines changed: 68 additions & 0 deletions

File tree

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// N-Queen
2+
// https://www.acmicpc.net/problem/9663
3+
const fs = require('fs');
4+
const stdin = (process.platform === 'linux'
5+
? fs.readFileSync('/dev/stdin').toString().trim()
6+
: `8`
7+
).split('\n');
8+
9+
const input = (() => {
10+
let line = 0;
11+
return () => stdin[line++];
12+
})();
13+
14+
function isValid(col) {
15+
for (let i = 0; i < col; i++) {
16+
if (
17+
chessBoard[i] === chessBoard[col] ||
18+
col - i === Math.abs(chessBoard[col] - chessBoard[i])
19+
) {
20+
return false;
21+
}
22+
}
23+
return true;
24+
}
25+
26+
function dfs(col) {
27+
if (col == N) {
28+
answer++;
29+
return;
30+
}
31+
32+
for (let i = 0; i < N; i++) {
33+
chessBoard[col] = i;
34+
if (isValid(col)) {
35+
dfs(col + 1);
36+
}
37+
}
38+
}
39+
40+
let answer = 0;
41+
42+
const N = parseInt(input());
43+
let chessBoard = Array(N).fill(0);
44+
45+
dfs(0);
46+
console.log(answer);
47+
48+
/*
49+
50+
## How
51+
๋ฌธ์ œ๋Š” ๋‘๋ฌธ์žฅ์œผ๋กœ ๊ตฌ์„ฑ๋˜์–ด์žˆ์—ˆ๊ณ  input๋„ 1๊ฐœ๋งŒ ๋ฐ›๊ฒŒ๋” ๋˜์–ด์žˆ๋Š” ๋ฌธ์ œ์˜€๋‹ค.
52+
53+
๋ฐฐ์—ด์— index๋ฅผ x๋ผ๊ณ  ๋‘๊ณ  x์— ๊ฐ index์— ์ดˆ๊ธฐํ™”๋˜๋Š” ๊ฐ’์„ y๋ผ๊ณ  ๋‘˜ ์ˆ˜ ์žˆ๋‹ค. ์ด๋Ÿฐ ํ˜•ํƒœ๋กœ N ํฌ๊ธฐ์˜ 1์ฐจ์› ๋ฐฐ์—ด์„ ๋งŒ๋“ ๋‹ค.
54+
55+
์žฌ๊ท€๋กœ ๊ฐ€๋Šฅํ•œ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ๋Š”๋ฐ ๋ช…๋ฐฑํ•˜๊ฒŒ ๋ถˆ๊ฐ€๋Šฅํ•œ ์ƒํ™ฉ์— ๋Œ€ํ•ด์„œ๋Š” ๊ฐ€์ง€๋ฅผ ์น  ์ˆ˜ ์žˆ๋‹ค.
56+
57+
๊ฐ€์ง€๋ฅผ ์น  ์ˆ˜ ์žˆ๋Š” ์ƒํ™ฉ์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.
58+
59+
1. ๊ฐ™์€ ํ–‰ ํ˜น์€ ์—ด์— ํ€ธ์ด ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ
60+
2. ๋Œ€๊ฐ์„ ์— ํ€ธ์ด ์กด์žฌํ•˜๋Š” ๊ฒฝ์šฐ
61+
62+
์ด ๋‘๊ฐ€์ง€์— ํ•ด๋‹นํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ์—๋งŒ true๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด์„œ ์žฌ๊ท€ ํ˜ธ์ถœ์„ ํ•˜๊ฒŒ๋” ์ฒ˜๋ฆฌํ•˜์˜€๋‹ค.
63+
64+
์žฌ๊ท€ํ•จ์ˆ˜์˜ index๊ฐ€ N๊นŒ์ง€ ๊ฐ€๋Š” ๊ฒฝ์šฐ count๋ฅผ ์ฆ๊ฐ€์‹œ์ผฐ๊ณ  ์ตœ์ข… count๊ฐ€ ์„œ๋กœ ๊ณต๊ฒฉํ•  ์ˆ˜ ์—†๊ฒŒ ๋†“๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜์ด๋‹ค.
65+
66+
## Retrospective
67+
68+
*/

0 commit comments

Comments
ย (0)