feat: add Swift codes for n_queens_problem article (#495)

* refactor: rename PreorderTraversalIIITemplate

* feat: add Swift codes for n_queens_problem article
pull/496/head
nuomi1 2 years ago committed by GitHub
parent 649d8c4c86
commit 170713c642
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -61,6 +61,7 @@ let package = Package(
.executable(name: "preorder_traversal_iii_template", targets: ["preorder_traversal_iii_template"]),
.executable(name: "permutations_i", targets: ["permutations_i"]),
.executable(name: "permutations_ii", targets: ["permutations_ii"]),
.executable(name: "n_queens", targets: ["n_queens"]),
],
targets: [
// helper
@ -122,5 +123,6 @@ let package = Package(
.executableTarget(name: "preorder_traversal_iii_template", dependencies: ["utils"], path: "chapter_backtracking", sources: ["preorder_traversal_iii_template.swift"]),
.executableTarget(name: "permutations_i", path: "chapter_backtracking", sources: ["permutations_i.swift"]),
.executableTarget(name: "permutations_ii", path: "chapter_backtracking", sources: ["permutations_ii.swift"]),
.executableTarget(name: "n_queens", path: "chapter_backtracking", sources: ["n_queens.swift"]),
]
)

@ -0,0 +1,67 @@
/**
* 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)
}
}
}
}

@ -53,7 +53,7 @@ func backtrack(state: inout [TreeNode], choices: [TreeNode], res: inout [[TreeNo
}
@main
enum preorder_traversal_iii_template {
enum PreorderTraversalIIITemplate {
/* Driver Code */
static func main() {
let root = TreeNode.listToTree(list: [1, 7, 3, 4, 5, 6, 7])

Loading…
Cancel
Save