forked from yuyongwei/Algorithms-In-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
nQueensII.swift
48 lines (40 loc) · 1.2 KB
/
nQueensII.swift
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
func solveNQueens(_ n: Int) -> [[String]] {
var result = [[Int]]()
func DFS(queens: [Int], xyDiff: [Int], xySum: [Int]) {
let p = queens.count
if p == n {
result.append(queens)
return
}
for q in 0..<n {
if !queens.contains(q) &&
!xyDiff.contains(p-q) &&
!xySum.contains(p+q) {
var tQ = queens
tQ.append(q)
var tDiff = xyDiff
tDiff.append(p-q)
var tSum = xySum
tSum.append(p+q)
DFS(queens: tQ, xyDiff: tDiff, xySum: tSum)
}
}
}
func helper(_ result: [[Int]]) -> [[String]] {
var str = [[String]]()
for sol in result {
var strSol = [String]()
for i in sol {
var s = String(repeating: ".", count: i)
s.append("Q")
let ss = String(repeating: ".", count: n-i-1)
s.append(ss)
strSol.append(s)
}
str.append(strSol)
}
return str
}
DFS(queens:[Int](), xyDiff:[Int](), xySum: [Int]())
return helper(result)
}