hello-algo/codes/swift/chapter_backtracking/n_queens.swift
Yudong Jin e720aa2d24
feat: Revised the book (#978)
* Sync recent changes to the revised Word.

* Revised the preface chapter

* Revised the introduction chapter

* Revised the computation complexity chapter

* Revised the chapter data structure

* Revised the chapter array and linked list

* Revised the chapter stack and queue

* Revised the chapter hashing

* Revised the chapter tree

* Revised the chapter heap

* Revised the chapter graph

* Revised the chapter searching

* Reivised the sorting chapter

* Revised the divide and conquer chapter

* Revised the chapter backtacking

* Revised the DP chapter

* Revised the greedy chapter

* Revised the appendix chapter

* Revised the preface chapter doubly

* Revised the figures
2023-12-02 06:21:34 +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)
}
}
}
}