File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
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
+
1
45
/**
2
46
* @param {number } n
3
47
* @return {string[][] }
You can’t perform that action at this time.
0 commit comments