Skip to content

Commit a2a27d0

Browse files
authored
Update 51-n-queens.js
1 parent dce846c commit a2a27d0

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

51-n-queens.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,47 @@
1+
/**
2+
* @param {number} n
3+
* @return {string[][]}
4+
*/
5+
const solveNQueens = function(n) {
6+
const res = []
7+
const chess = Array.from({length: n}, () => new Array(n).fill('.'))
8+
bt(res, chess, 0)
9+
return res
10+
}
11+
12+
function bt(res, chess, row) {
13+
if(row === chess.length) {
14+
res.push(build(chess))
15+
return
16+
}
17+
for(let i = 0, num = chess[0].length; i < num; i++) {
18+
if(valid(chess, row, i)) {
19+
chess[row][i] = 'Q'
20+
bt(res, chess, row + 1)
21+
chess[row][i] = '.'
22+
}
23+
}
24+
}
25+
26+
function valid(chess, row, col) {
27+
for(let i = row - 1; i >= 0; i--) {
28+
if(chess[i][col] === 'Q') return false
29+
}
30+
for(let i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
31+
if(chess[i][j] === 'Q') return false
32+
}
33+
for(let i = row - 1, j = col + 1; i >= 0 && j < chess[0].length; i--, j++) {
34+
if(chess[i][j] === 'Q') return false
35+
}
36+
return true
37+
}
38+
39+
function build(chess) {
40+
return chess.map(el => el.join(''))
41+
}
42+
43+
// another
44+
145
/**
246
* @param {number} n
347
* @return {string[][]}

0 commit comments

Comments
 (0)