-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
67 lines (57 loc) · 1.63 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// define a variable to keep track of the solutions
let solutions = [];
// define a function to check if a given position is safe
function isSafe(board, row, col) {
// check the row
for (let i = 0; i < col; i++) {
if (board[row][i] === 1) {
return false;
}
}
// check the upper diagonal
for (let i = row, j = col; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] === 1) {
return false;
}
}
// check the lower diagonal
for (let i = row, j = col; j >= 0 && i < board.length; i++, j--) {
if (board[i][j] === 1) {
return false;
}
}
// if the position is safe, return true
return true;
}
// define a function to solve the problem using backtracking
function solveQueens(board, col) {
// base case: if all queens are placed, add the solution to the solutions array and return
if (col >= board.length) {
solutions.push(board.map(row => row.slice()));
return;
}
// try placing a queen in each row of the current column
for (let i = 0; i < board.length; i++) {
if (isSafe(board, i, col)) {
board[i][col] = 1;
solveQueens(board, col + 1);
board[i][col] = 0;
}
}
}
// define a function to print the solutions
function printSolutions(solutions) {
for (let i = 0; i < solutions.length; i++) {
console.log(`Solution ${i+1}:`);
for (let j = 0; j < solutions[i].length; j++) {
console.log(solutions[i][j].join(" "));
}
console.log("");
}
}
// initialize an empty 8x8 chessboard
let board = new Array(8).fill(null).map(() => new Array(8).fill(0));
// solve the problem
solveQueens(board, 0);
// print the solutions
printSolutions(solutions);