Skip to content

Commit fd42583

Browse files
authored
Create 51-n-queens.js
1 parent 3f497fc commit fd42583

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

51-n-queens.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @param {number} n
3+
* @return {string[][]}
4+
*/
5+
const solveNQueens = function(n) {
6+
const res = []
7+
bt(res, n)
8+
return res
9+
}
10+
11+
function bt(res, n, board = [], r = 0) {
12+
if (r === n) {
13+
res.push(board.map(c => '.'.repeat(c) + 'Q' + '.'.repeat(n - c - 1)))
14+
return
15+
}
16+
for (let c = 0; c < n; c++) {
17+
if (
18+
!board.some(
19+
(bc, br) => bc === c || bc === c + r - br || bc === c - r + br
20+
)
21+
) {
22+
board.push(c)
23+
bt(res, n, board, r + 1)
24+
board.pop()
25+
}
26+
}
27+
}

0 commit comments

Comments
 (0)