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

Commit c7228e3

Browse files
author
zongyanqi
committed
add 051-N-Queens
1 parent eb49db3 commit c7228e3

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

051-N-Queens.js

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/**
2+
* https://leetcode.com/problems/n-queens/description/
3+
* Difficulty:Hard
4+
*
5+
* The n-queens puzzle is the problem of placing n queens on an n×n chessboard
6+
* such that no two queens attack each other.
7+
*
8+
* Given an integer n, return all distinct solutions to the n-queens puzzle.
9+
* Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
10+
*
11+
* For example,
12+
* There exist two distinct solutions to the 4-queens puzzle:
13+
* [
14+
* [".Q..", // Solution 1
15+
* "...Q",
16+
* "Q...",
17+
* "..Q."],
18+
*
19+
* ["..Q.", // Solution 2
20+
* "Q...",
21+
* "...Q",
22+
* ".Q.."]
23+
* ]
24+
* 2,1 3,2
25+
*/
26+
27+
/**
28+
* @param {number} n
29+
* @return {string[][]}
30+
*/
31+
var solveNQueens = function (n) {
32+
var ret = [];
33+
var board = [];
34+
for (var i = 0; i < n; i++) {
35+
board.push(new Array(n).fill('.'));
36+
}
37+
helper(board, 0, ret);
38+
return ret;
39+
};
40+
41+
function helper(board, col, ret) {
42+
if (col === board.length) {
43+
ret.push(construct(board));
44+
} else {
45+
for (var i = 0; i < board.length; i++) {
46+
if (check(board, i, col)) {
47+
board[i][col] = 'Q';
48+
helper(board, col + 1, ret);
49+
board[i][col] = '.';
50+
}
51+
}
52+
}
53+
}
54+
55+
function check(board, x, y) {
56+
for (var i = 0; i < board.length; i++) {
57+
for (var j = 0; j < y; j++) {
58+
if (board[i][j] === 'Q' &&
59+
(i === x || i + j === x + y || i + y === j + x)) return false;
60+
}
61+
}
62+
return true;
63+
}
64+
function construct(board) {
65+
return board.map(arr => arr.join(''));
66+
}
67+
console.log(solveNQueens(4));

0 commit comments

Comments
 (0)