-
Notifications
You must be signed in to change notification settings - Fork 3
/
N-Queen.swift
53 lines (44 loc) · 1.4 KB
/
N-Queen.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
49
50
51
52
53
import Foundation
let N = Int(readLine()!)!
func solution(N: Int) -> Int {
var board = ChessBoard(n: N)
board.nQueen(row: 0)
return board.count
}
print(solution(N: N))
struct ChessBoard {
var size: Int
var isUsed1: [Bool]
var isUsed2: [Bool]
var isUsed3: [Bool]
var count = 0
init(n: Int) {
self.size = n
self.isUsed1 = Array(repeating: false, count: n)
self.isUsed2 = Array(repeating: false, count: 2 * n - 1)
self.isUsed3 = Array(repeating: false, count: 2 * n - 1)
}
mutating func nQueen(row: Int) {
if row == self.size {
self.count += 1
return
}
for col in 0..<self.size {
if self.isOkayToPut(row: row, col: col) {
self.isUsed1[col] = true
self.isUsed2[row + col] = true
self.isUsed3[row - col + self.size - 1] = true
self.nQueen(row: row + 1)
self.isUsed1[col] = false
self.isUsed2[row + col] = false
self.isUsed3[row - col + self.size - 1] = false
}
}
}
func isOkayToPut(row: Int, col: Int) -> Bool {
if self.isUsed1[col] == true { return false }
if self.isUsed2[row + col] == true { return false }
if self.isUsed3[row - col + self.size - 1] == true { return false }
return true
}
}