Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitc7228e3

Browse files
author
zongyanqi
committed
add 051-N-Queens
1 parenteb49db3 commitc7228e3

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

‎051-N-Queens.js

Lines changed: 67 additions & 0 deletions
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+
varsolveNQueens=function(n){
32+
varret=[];
33+
varboard=[];
34+
for(vari=0;i<n;i++){
35+
board.push(newArray(n).fill('.'));
36+
}
37+
helper(board,0,ret);
38+
returnret;
39+
};
40+
41+
functionhelper(board,col,ret){
42+
if(col===board.length){
43+
ret.push(construct(board));
44+
}else{
45+
for(vari=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+
functioncheck(board,x,y){
56+
for(vari=0;i<board.length;i++){
57+
for(varj=0;j<y;j++){
58+
if(board[i][j]==='Q'&&
59+
(i===x||i+j===x+y||i+y===j+x))returnfalse;
60+
}
61+
}
62+
returntrue;
63+
}
64+
functionconstruct(board){
65+
returnboard.map(arr=>arr.join(''));
66+
}
67+
console.log(solveNQueens(4));

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp