This solution is more specific to leet code problem.
If you want only solution for possible option please print board array- or Refer - N-Queen : Check if possible to place in NxN
const N = 4;
let allPossibleArray = [];
function isSafe(board, row, col, N) {
for (let i = row - 1; i >= 0; i--) if (board[i][col] == 1) return false;
for (let i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--)
if (board[i][j] == 1) return false;
for (let i = row - 1, j = col + 1; i >= 0 && j < N; i--, j++)
if (board[i][j] == 1) return false;
return true;
}
function solveNQUtil(board, N, row) {
if (row === N) {
let tm = [];
for (let i = 0; i < N; i++) {
let s = "";
for (let j = 0; j < N; j++) {
if (board[i][j] == 1) s += "Q";
else s += ".";
}
tm.push(s);
}
allPossibleArray.push(tm);
}
for (let col = 0; col < N; col++) {
if (isSafe(board, row, col, N) == true) {
board[row][col] = 1;
solveNQUtil(board, N, row + 1);
board[row][col] = 0;
}
}
return false;
}
function solveNQ() {
let board = [
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
];
solveNQUtil(board, N, 0);
return allPossibleArray;
}
console.log(solveNQ());
Top comments (0)