File tree Expand file tree Collapse file tree 2 files changed +43
-0
lines changed Expand file tree Collapse file tree 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 565648|[ Rotate Image] ( ./0048-rotate-image.js ) |Medium|
575749|[ Group Anagrams] ( ./0049-group-anagrams.js ) |Medium|
585850|[ Pow(x, n)] ( ./0050-powx-n.js ) |Medium|
59+ 51|[ N-Queens] ( ./0051-n-queens.js ) |Hard|
596053|[ Maximum Subarray] ( ./0053-maximum-subarray.js ) |Easy|
606154|[ Spiral Matrix] ( ./0054-spiral-matrix.js ) |Medium|
616257|[ Insert Interval] ( ./0057-insert-interval.js ) |Medium|
You can’t perform that action at this time.
0 commit comments