-
Notifications
You must be signed in to change notification settings - Fork 91
/
NQueens.js
92 lines (82 loc) · 1.69 KB
/
NQueens.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
NQueens
https://leetcode.com/problems/n-queens/description/
Example:
Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
*/
/**
* @param {number} n
* @return {string[][]}
*/
var solveNQueens = function (n) {
var sol = [];
solveNQueensAux(n, 0, new Set(), new Set(), new Set(), [], sol);
return parseSolutions(sol, n);
};
var solveNQueensAux = function (
n,
row,
diagonalDiffs,
diagonalSums,
cols,
currentSol,
sol
) {
if (row == n) {
sol.push(currentSol);
return;
}
for (var i = 0; i < n; i++) {
const diagonalDiff = i - row;
const diagonalSum = i + row;
if (
!diagonalDiffs.has(diagonalDiff) &&
!cols.has(i) &&
!diagonalSums.has(diagonalSum)
) {
diagonalDiffs.add(diagonalDiff);
diagonalSums.add(diagonalSum);
cols.add(i);
solveNQueensAux(
n,
row + 1,
diagonalDiffs,
diagonalSums,
cols,
[...currentSol, ...[[row, i]]],
sol
);
cols.delete(i);
diagonalDiffs.delete(diagonalDiff);
diagonalSums.delete(diagonalSum);
}
}
};
var parseSolutions = function (sols, n) {
var matrixes = [];
for (var i = 0; i < sols.length; i++) {
var sol = sols[i];
var matrix = [];
for (var row = 0; row < n; row++) {
matrix[row] = [];
const queenPos = sol[row];
for (var col = 0; col < n; col++) {
matrix[row] += queenPos[1] == col ? "Q" : ".";
}
}
matrixes.push(matrix);
}
return matrixes;
};
module.exports.solveNQueens = solveNQueens;