forked from lazzzis/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
72 lines (65 loc) · 1.44 KB
/
Copy pathmain.js
File metadata and controls
72 lines (65 loc) · 1.44 KB
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
/**
* @param {number} n
* @return {string[][]}
*/
var solveNQueens = function(n) {
const grids = Array.from({ length: n }, () => {
return Array.from({ length: n }, () => '.')
})
const ans = []
function isConflicted (x, y) {
for (let i = 0; i < x; i++) {
if (grids[i][y] === 'Q') {
return true
}
}
let i = x - 1
let j = y - 1
while (i >= 0 && j >= 0) {
if (grids[i--][j--] === 'Q') {
return true
}
}
i = x - 1
j = y + 1
while (i >= 0 && j < n) {
if (grids[i--][j++] === 'Q') {
return true
}
}
return false
}
function mirror (grids) {
return grids.map((item) => item.slice().reverse())
}
function fillGrids (x, callback) {
if (x >= n) {
return callback(grids)
}
for (let i = 0; i < n; i++) {
if (!isConflicted(x, i)) {
grids[x][i] = 'Q'
fillGrids(x + 1, callback)
grids[x][i] = '.'
}
}
}
for (let i = 0; i < Math.floor(n / 2); i++) {
grids[0][i] = 'Q'
fillGrids(1, (grids) => {
ans.push(grids.map(item => item.slice()), mirror(grids))
})
grids[0][i] = '.'
}
if (n % 2 === 1) {
grids[0][Math.floor(n / 2)] = 'Q'
fillGrids(1, (grids) => {
ans.push(grids.map(item => item.slice()))
})
grids[0][Math.floor(n / 2)] = '.'
}
return ans.map((grids) => {
return grids.map(row => row.join(''))
})
};
console.log(solveNQueens(6))