Initial data commit
This commit is contained in:
parent
72d218235f
commit
f23f22d71c
199087 changed files with 3378941 additions and 0 deletions
33
Task/N-queens-problem/JavaScript/n-queens-problem-1.js
Normal file
33
Task/N-queens-problem/JavaScript/n-queens-problem-1.js
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
function queenPuzzle(rows, columns) {
|
||||
if (rows <= 0) {
|
||||
return [[]];
|
||||
} else {
|
||||
return addQueen(rows - 1, columns);
|
||||
}
|
||||
}
|
||||
|
||||
function addQueen(newRow, columns, prevSolution) {
|
||||
var newSolutions = [];
|
||||
var prev = queenPuzzle(newRow, columns);
|
||||
for (var i = 0; i < prev.length; i++) {
|
||||
var solution = prev[i];
|
||||
for (var newColumn = 0; newColumn < columns; newColumn++) {
|
||||
if (!hasConflict(newRow, newColumn, solution))
|
||||
newSolutions.push(solution.concat([newColumn]))
|
||||
}
|
||||
}
|
||||
return newSolutions;
|
||||
}
|
||||
|
||||
function hasConflict(newRow, newColumn, solution) {
|
||||
for (var i = 0; i < newRow; i++) {
|
||||
if (solution[i] == newColumn ||
|
||||
solution[i] + i == newColumn + newRow ||
|
||||
solution[i] - i == newColumn - newRow) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
console.log(queenPuzzle(8,8));
|
||||
Loading…
Add table
Add a link
Reference in a new issue