You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
hello-algo/codes/swift/chapter_backtracking/n_queens.swift

68 lines
2.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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