forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0051-n-queens.swift
37 lines (33 loc) · 1010 Bytes
/
0051-n-queens.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
class Solution {
func solveNQueens(_ n: Int) -> [[String]] {
var res = [[String]]()
var col = Set<Int>()
var posDiag = Set<Int>()
var negDiag = Set<Int>()
var cur = Array(repeating: Array(repeating: ".", count: n), count: n)
func dfs(_ r: Int) {
if r == n {
let copy = cur.map { $0.joined() }
print(copy)
res.append(copy)
return
}
for c in 0..<n {
if col.contains(c) || posDiag.contains(r + c) || negDiag.contains(r - c) {
continue
}
col.insert(c)
posDiag.insert(r + c)
negDiag.insert(r - c)
cur[r][c] = "Q"
dfs(r + 1)
col.remove(c)
posDiag.remove(r + c)
negDiag.remove(r - c)
cur[r][c] = "."
}
}
dfs(0)
return res
}
}