-
Notifications
You must be signed in to change notification settings - Fork 7
/
52-N-Queens-II.js
43 lines (36 loc) · 1.05 KB
/
52-N-Queens-II.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
/**
* @param {number} n
* @return {number}
*/
const totalNQueens = (n) => {
const board = new Array(n).fill(null).map(() => new Array(n).fill('.'));
const result = [];
const isValid = (row, col) => {
for (let i = 0; i < row; i++) {
if (board[i][col] === 'Q') return false;
}
for (let i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (board[i][j] === 'Q') return false;
}
for (let i = row - 1, j = col + 1; i >= 0 && j <= n - 1; i--, j++) {
if (board[i][j] === 'Q') return false;
}
return true;
};
const helper = (row) => {
if (row === n) {
const option = board.map((row) => row.join(''));
result.push(option);
return;
}
for (let col = 0; col < n; col++) {
if (isValid(row, col)) {
board[row][col] = 'Q';
helper(row + 1);
board[row][col] = '.';
}
}
};
helper(0);
return result.length;
};