-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path51.n-queens.beat-0.js
107 lines (97 loc) · 2.24 KB
/
51.n-queens.beat-0.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
* @lc app=leetcode id=51 lang=javascript
*
* [51] N-Queens
*
* https://leetcode.com/problems/n-queens/description/
*
* algorithms
* Hard (36.36%)
* Total Accepted: 120K
* Total Submissions: 330K
* Testcase Example: '4'
*
* The n-queens puzzle is the problem of placing n queens on an n×n chessboard
* such that no two queens attack each other.
*
*
*
* Given an integer n, return all distinct solutions to the n-queens puzzle.
*
* Each solution contains a distinct board configuration of the n-queens'
* placement, where 'Q' and '.' both indicate a queen and an empty space
* respectively.
*
* Example:
*
*
* Input: 4
* Output: [
* [".Q..", // Solution 1
* "...Q",
* "Q...",
* "..Q."],
*
* ["..Q.", // Solution 2
* "Q...",
* "...Q",
* ".Q.."]
* ]
* Explanation: There exist two distinct solutions to the 4-queens puzzle as
* shown above.
*
*
*/
/**
* @param {number} n
* @return {string[][]}
*/
var solveNQueens = function(n) {
const nQueensOnDiagonal = generateNQueensOnDiagonal(n);
const solutions = genPermutations(nQueensOnDiagonal);
return solutions.filter(board => hasNoTwoQueenOnDiagonal(board));
};
function generateNQueensOnDiagonal(n) {
const nQueensOnDiagonal = [];
for (let i = 0; i < n; i++) {
const row = new Array(n).fill('.');
row[i] = 'Q';
nQueensOnDiagonal.push(row.join(''));
}
return nQueensOnDiagonal;
}
function genPermutations(l) {
const ans = [];
permutate(l.length, sol => ans.push(sol));
return ans;
function permutate(n, callback) {
if (n === 1)
callback([ ...l ]);
for (let i = 0; i < n; i++) {
[ l[i], l[n - 1] ] = [ l[n - 1], l[i] ];
permutate(n - 1, callback);
[ l[i], l[n - 1] ] = [ l[n - 1], l[i] ];
}
return;
}
}
function hasNoTwoQueenOnDiagonal(board) {
const n = board.length;
for (let i = 0; i < n - 1; i++) {
const j = findQueenIndexInRow(board[i]);
for (let k = 1; k < n - i; k++) {
if (
board[i + k][j - k] === 'Q' ||
board[i + k][j + k] === 'Q'
)
return false;
}
}
return true;
}
function findQueenIndexInRow(row) {
for (let j = 0; j < row.length; j++)
if (row[j] === 'Q')
return j;
return -1;
}