Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit b5cfbd2

Browse files
committed
Add solution #51
1 parent d10ab86 commit b5cfbd2

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

0051-n-queens.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@
5656
48|[Rotate Image](./0048-rotate-image.js)|Medium|
5757
49|[Group Anagrams](./0049-group-anagrams.js)|Medium|
5858
50|[Pow(x, n)](./0050-powx-n.js)|Medium|
59+
51|[N-Queens](./0051-n-queens.js)|Hard|
5960
53|[Maximum Subarray](./0053-maximum-subarray.js)|Easy|
6061
54|[Spiral Matrix](./0054-spiral-matrix.js)|Medium|
6162
57|[Insert Interval](./0057-insert-interval.js)|Medium|

0 commit comments

Comments
 (0)