N 皇后
const solveNQueens = function (n) {
const cols = new Set();
const left = new Set();
const right = new Set();
const result = [];
valid(0, n, cols, left, right, result, []);
return draw(result, n);
};
const valid = function (row, n, cols, left, right, result, temp) {
if (row === n) {
result.push([...temp]);
temp = [];
}
for (let i = 0; i < n; i++) {
if (!cols.has(i) && !right.has(row - i) && !left.has(row + i)) {
cols.add(i);
left.add(row + i);
right.add(row - i);
temp[row] = i;
valid(row + 1, n, cols, left, right, result, temp);
cols.delete(i);
left.delete(row + i);
right.delete(row - i);
}
}
};
function draw(arr, n) {
let res = [];
arr.forEach((item) => {
let sub = [];
item.forEach((i) => {
let temp = Array(n).fill(".");
temp[i] = "Q";
sub.push(temp.join(""));
});
res.push(sub);
});
return res;
}