|
| 1 | +# 51. N-Queens |
| 2 | + |
| 3 | +### 2020年07月29日 |
| 4 | + |
| 5 | +The *n*-queens puzzle is the problem of placing *n* queens on an *n*×ばつ*n* chessboard such that no two queens attack each other. |
| 6 | + |
| 7 | + |
| 8 | + |
| 9 | + |
| 10 | +# Solution |
| 11 | + |
| 12 | +```swift |
| 13 | + |
| 14 | +class Solution { |
| 15 | + |
| 16 | + private func checkLine(y: Int, n: Int, col: inout [Bool], row: inout [Int], d1: inout [Bool], d2: inout [Bool], res: inout [[String]]) { |
| 17 | + if y == n { |
| 18 | + var temp = [String]() |
| 19 | + for i in 0..<n { |
| 20 | + var line = Array<Character>.init(repeating: ".", count: n) |
| 21 | + line[row[i]] = "Q" |
| 22 | + temp.append(String(line)) |
| 23 | + } |
| 24 | + res.append(temp) |
| 25 | + } else { |
| 26 | + for x in 0..<n { |
| 27 | + if !col[x], !d1[x + y], !d2[x - y + (n - 1)] { |
| 28 | + col[x] = true |
| 29 | + d1[x+y] = true |
| 30 | + d2[x - y + (n - 1)] = true |
| 31 | + row[y] = x |
| 32 | + checkLine(y: y + 1, n: n, col: &col, row: &row, d1: &d1, d2: &d2, res: &res) |
| 33 | + col[x] = false |
| 34 | + d1[x+y] = false |
| 35 | + d2[x - y + (n - 1)] = false |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + func solveNQueens(_ n: Int) -> [[String]] { |
| 42 | + var res = [[String]]() |
| 43 | + guard n > 0 else { |
| 44 | + return res |
| 45 | + } |
| 46 | + var col = [Bool].init(repeating: false, count: n) |
| 47 | + var row = [Int].init(repeating: 0, count: n) |
| 48 | + var d1 = [Bool].init(repeating: false, count: (2 * n ) - 1) |
| 49 | + var d2 = [Bool].init(repeating: false, count: (2 * n ) - 1) |
| 50 | + checkLine(y: 0, n: n, col: &col, row: &row, d1: &d1, d2: &d2, res: &res) |
| 51 | + return res |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +``` |
0 commit comments