
https://www.youtube.com/watch?v=lYo7TF0_d-o


/* _
___ ___ | |_ _____ _ __ ___
/ __|/ _ \| \ \ / / _ \ '__/ __|
\__ \ (_) | |\ V / __/ | \__ \
|___/\___/|_| \_/ \___|_| |___/
*/
// hint: you'll need to do a full-search of all possible arrangements of pieces!
// (There are also optimizations that will allow you to skip a lot of the dead search space)
// take a look at solversSpec.js to see what the tests are expecting
// n이 주어졌을 때 n rooks 문제의 해답 한 개를 반환합니다.
// 반환 값은 체스 판을 나타내는 2차원 배열입니다.
// [
// [0,0,0,0],
// [0,0,0,0],
// [0,0,0,0],
// [0,0,0,0]
// ]
window.findNRooksSolution = function (n) {
var solution = [];
fucntion;
var board = new Board({ n: n }); //체스판
let buckets = board.rows(); //체스판의 배열
for (let i = 0; i < buckets.length; i++) {
for (let j = 0; j < buckets[i].length; j++) {
board.togglePiece(i, j);
if (board.hasAnyRooksConflictsOn(i, j)) {
board.togglePiece(i, j);
}
}
}
console.log('Single solution for ' + n + ' rooks:', JSON.stringify(solution));
return buckets;
};
// n이 주어졌을 때 n rooks 문제의 전체 해답 개수를 반환합니다.
// 반환 값은 정수입니다.
window.countNRooksSolutions = function (n) {
var board = new Board({ n });
var boardPan = board.rows();
var solutionCount = 0;
function recur(colIndex) {
if (colIndex === boardPan.length) {
solutionCount++;
}
for (let i = 0; i < boardPan.length; i++) {
boardPan[i][colIndex] = 1;
if (!board.hasAnyRooksConflicts()) {
recur(colIndex + 1);
}
boardPan[i][colIndex] = 0;
}
}
recur(0);
console.log('Number of solutions for ' + n + ' rooks:', solutionCount);
return solutionCount;
};
// n이 주어졌을 때 n queens 문제의 해답 한 개를 반환합니다.
// 반환 값은 체스 판을 나타내는 2차원 배열입니다.
window.findNQueensSolution = function (n) {
let board = new Board({ n: n });
let solution = undefined; // 리턴할 값
// n이 2혹은 3일 때는 말을 n개를 올릴 수가 없음
if (n === 2 || n === 3 || n === 0) {
return board.rows();
}
function recursion(row) {
if (row === n) {
//row가 n과 같으면 다 돌았으니까 리턴
solution = board.rows();
return solution;
} else {
// 아니면 말을 올린다.
for (let i = 0; i < n; i++) {
board.togglePiece(row, i);
if (!board.hasAnyQueenConflictsOn(row, i)) {
recursion(row + 1); // 충돌이 없으면 다음 행으로 재귀
}
if (solution) {
// 말이 다 놓아졌으면 재귀에서 빠져나오고
break;
}
board.togglePiece(row, i); // 그렇지 않으면 다시 말을 놓는다.
}
}
}
recursion(0);
console.log(
'Single solution for ' + n + ' queens:',
JSON.stringify(solution)
);
return solution;
};
// n이 주어졌을 때 n queens 문제의 전체 해답 개수를 반환합니다.
// 반환 값은 정수입니다.
window.countNQueensSolutions = function (n) {
let solutionCount = 0;
if (n === 0 || n === 2 || n === 3) {
return 0;
}
let board = new Board({ n: n });
let solution = undefined;
function recursion(row) {
if (row === n) {
solution = board.rows();
return solution;
} else {
for (let i = 0; i < n; i++) {
board.togglePiece(row, i);
if (!board.hasAnyQueenConflictsOn(row, i)) {
recursion(row + 1);
}
if (solution) {
solutionCount++;
solution = undefined;
}
board.togglePiece(row, i);
}
}
}
recursion(0);
console.log('Number of solutions for ' + n + ' queens:', solutionCount);
return solutionCount;
};