Skip to content

Commit a335e08

Browse files
committed
Create 0051-n-queens.swift
1 parent b3ed6ee commit a335e08

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

swift/0051-n-queens.swift

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
class Solution {
2+
func solveNQueens(_ n: Int) -> [[String]] {
3+
var res = [[String]]()
4+
var col = Set<Int>()
5+
var posDiag = Set<Int>()
6+
var negDiag = Set<Int>()
7+
var cur = Array(repeating: Array(repeating: ".", count: n), count: n)
8+
9+
func dfs(_ r: Int) {
10+
if r == n {
11+
let copy = cur.map { $0.joined() }
12+
print(copy)
13+
res.append(copy)
14+
return
15+
}
16+
17+
for c in 0..<n {
18+
if col.contains(c) || posDiag.contains(r + c) || negDiag.contains(r - c) {
19+
continue
20+
}
21+
col.insert(c)
22+
posDiag.insert(r + c)
23+
negDiag.insert(r - c)
24+
cur[r][c] = "Q"
25+
dfs(r + 1)
26+
col.remove(c)
27+
posDiag.remove(r + c)
28+
negDiag.remove(r - c)
29+
cur[r][c] = "."
30+
}
31+
}
32+
33+
dfs(0)
34+
35+
return res
36+
}
37+
}

0 commit comments

Comments
 (0)