hello-algo/codes/swift/chapter_backtracking/n_queens.swift
nuomi1 170713c642
feat: add Swift codes for n_queens_problem article (#495)
* refactor: rename PreorderTraversalIIITemplate

* feat: add Swift codes for n_queens_problem article
2023-05-15 01:13:17 +08:00

67 lines
2.2 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 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
// ( 线 线)
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)
}
}
}
}