File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments