File tree 2 files changed +43
-0
lines changed
2 files changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * 51. N-Queens
3
+ * https://leetcode.com/problems/n-queens/
4
+ * Difficulty: Hard
5
+ *
6
+ * The n-queens puzzle is the problem of placing n queens on an n x n
7
+ * chessboard such that no two queens attack each other.
8
+ *
9
+ * Given an integer n, return all distinct solutions to the n-queens
10
+ * puzzle. You may return the answer in any order.
11
+ *
12
+ * Each solution contains a distinct board configuration of the n-queens'
13
+ * placement, where 'Q' and '.' both indicate a queen and an empty space,
14
+ * respectively.
15
+ */
16
+
17
+ /**
18
+ * @param {number } n
19
+ * @return {string[][] }
20
+ */
21
+ var solveNQueens = function ( n ) {
22
+ const result = [ ] ;
23
+ backtrack ( result , n ) ;
24
+ return result ;
25
+ } ;
26
+
27
+ function backtrack ( result , n , board = [ ] , size = 0 ) {
28
+ if ( n === size ) {
29
+ result . push ( board . map ( s => `${ '.' . repeat ( s ) } Q${ '.' . repeat ( n - s - 1 ) } ` ) ) ;
30
+ } else {
31
+ for ( let rows = 0 ; rows < n ; rows ++ ) {
32
+ const isValid = ! board . some ( ( i , j ) => {
33
+ return i === rows || i === rows + size - j || i === rows - size + j ;
34
+ } ) ;
35
+ if ( isValid ) {
36
+ board . push ( rows ) ;
37
+ backtrack ( result , n , board , size + 1 ) ;
38
+ board . pop ( ) ;
39
+ }
40
+ }
41
+ }
42
+ }
Original file line number Diff line number Diff line change 56
56
48|[ Rotate Image] ( ./0048-rotate-image.js ) |Medium|
57
57
49|[ Group Anagrams] ( ./0049-group-anagrams.js ) |Medium|
58
58
50|[ Pow(x, n)] ( ./0050-powx-n.js ) |Medium|
59
+ 51|[ N-Queens] ( ./0051-n-queens.js ) |Hard|
59
60
53|[ Maximum Subarray] ( ./0053-maximum-subarray.js ) |Easy|
60
61
54|[ Spiral Matrix] ( ./0054-spiral-matrix.js ) |Medium|
61
62
57|[ Insert Interval] ( ./0057-insert-interval.js ) |Medium|
You can’t perform that action at this time.
0 commit comments