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

Commit c03198b

Browse files
committed
feat: N皇后
1 parent 4f5fbd4 commit c03198b

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

递归与回溯/N 皇后-51.js

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/**
2+
* @param {number} n
3+
* @return {string[][]}
4+
*/
5+
let solveNQueens = function (n) {
6+
let res = []
7+
8+
// 已摆放皇后的的列下标
9+
let columns = []
10+
// 已摆放皇后的对角线1下标 左下 -> 右上
11+
// 计算某个坐标是否在这个对角线的方式是「行下标 + 列下标」是否相等
12+
let dia1 = []
13+
// 已摆放皇后的对角线2下标 左上 -> 右下
14+
// 计算某个坐标是否在这个对角线的方式是「行下标 - 列下标」是否相等
15+
let dia2 = []
16+
17+
// 尝试在一个n皇后问题中 摆放第index行内的皇后位置
18+
let putQueen = (rowIndex, row) => {
19+
if (rowIndex === n) {
20+
res.push(generateBoard(row))
21+
return
22+
}
23+
24+
// 尝试摆第index行的皇后 尝试[0, n-1]列
25+
for (let columnIndex = 0; columnIndex < n; columnIndex++) {
26+
// 在列上不冲突
27+
let columnNotConflict = !columns[columnIndex]
28+
// 在对角线1上不冲突
29+
let dia1NotConflict = !dia1[rowIndex + columnIndex]
30+
// 在对角线2上不冲突
31+
let dia2NotConflict = !dia2[rowIndex - columnIndex]
32+
33+
if (columnNotConflict && dia1NotConflict && dia2NotConflict) {
34+
35+
columns[columnIndex] = true
36+
dia1[rowIndex + columnIndex] = true
37+
dia2[rowIndex - columnIndex] = true
38+
39+
putQueen(rowIndex + 1, row.concat(columnIndex))
40+
41+
columns[columnIndex] = false
42+
dia1[rowIndex + columnIndex] = false
43+
dia2[rowIndex - columnIndex] = false
44+
}
45+
}
46+
}
47+
48+
putQueen(0, [])
49+
50+
return res
51+
}
52+
53+
function generateBoard(row) {
54+
let n = row.length
55+
let res = []
56+
for(let y = 0; y < n; y++) {
57+
let cur = ''
58+
for (let x = 0; x < n; x++) {
59+
if (x === row[y]) {
60+
cur += 'Q'
61+
}else {
62+
cur += '.'
63+
}
64+
}
65+
res.push(cur)
66+
}
67+
return res
68+
}
69+
70+
console.log(solveNQueens(4))

0 commit comments

Comments
 (0)