-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathn-queens.js
More file actions
52 lines (43 loc) · 845 Bytes
/
n-queens.js
File metadata and controls
52 lines (43 loc) · 845 Bytes
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
// Source : https://leetcode.com/problems/n-queens/
// Author : Han Zichi
// Date : 2015-09-11
/**
* @param {number} n
* @return {string[][]}
*/
var pos, ans;
function check(r, c) {
for (var i = 1; i < r; i++) {
if (Math.abs(i - r) === Math.abs(pos[i] - c))
return true;
if (c === pos[i])
return true;
}
return false;
}
function dfs(r, n) {
if (r === n + 1) {
var tmp = [];
for (var i = 1; i <= n; i++) {
var str = '';
for (var j = 1; j <= n; j++)
if (pos[i] === j)
str += 'Q';
else
str += '.';
tmp.push(str);
}
ans.push(tmp);
return;
}
for (var i = 1; i <= n; i++) {
if (check(r, i)) continue;
pos[r] = i;
dfs(r + 1, n);
}
}
var solveNQueens = function(n) {
pos = [], ans = [];
dfs(1, n);
return ans;
};