hello-algo/codes/swift/chapter_backtracking/n_queens.swift

68 lines
2.2 KiB
Swift
Raw Normal View History

/**
* File: n_queens.swift
* Created Time: 2023-05-14
* Author: nuomi1 (nuomi1@qq.com)
*/
/* N */
func backtrack(row: Int, n: Int, state: inout [[String]], res: inout [[[String]]], cols: inout [Bool], diags1: inout [Bool], diags2: inout [Bool]) {
//
if row == n {
res.append(state)
return
}
//
for col in 0 ..< n {
// 线线
let diag1 = row - col + n - 1
let diag2 = row + col
// 线线
2023-06-21 02:56:28 +08:00
if !cols[col] && !diags1[diag1] && !diags2[diag2] {
//
state[row][col] = "Q"
cols[col] = true
diags1[diag1] = true
diags2[diag2] = true
//
backtrack(row: row + 1, n: n, state: &state, res: &res, cols: &cols, diags1: &diags1, diags2: &diags2)
// 退
state[row][col] = "#"
cols[col] = false
diags1[diag1] = false
diags2[diag2] = false
}
}
}
/* N */
func nQueens(n: Int) -> [[[String]]] {
// n*n 'Q' '#'
var state = Array(repeating: Array(repeating: "#", count: n), count: n)
var cols = Array(repeating: false, count: n) //
var diags1 = Array(repeating: false, count: 2 * n - 1) // 线
var diags2 = Array(repeating: false, count: 2 * n - 1) // 线
var res: [[[String]]] = []
backtrack(row: 0, n: n, state: &state, res: &res, cols: &cols, diags1: &diags1, diags2: &diags2)
return res
}
@main
enum NQueens {
/* Driver Code */
static func main() {
let n = 4
let res = nQueens(n: n)
print("输入棋盘长宽为 \(n)")
print("皇后放置方案共有 \(res.count)")
for state in res {
print("--------------------")
for row in state {
print(row)
}
}
}
}