/** * File: n_queens.kt * Created Time: 2024-01-25 * Author: curtishd (1023632660@qq.com) */ package chapter_backtracking.n_queens /* 回溯演算法:n 皇后 */ fun backtrack( row: Int, n: Int, state: List>, res: MutableList>?>, cols: BooleanArray, diags1: BooleanArray, diags2: BooleanArray ) { // 當放置完所有行時,記錄解 if (row == n) { val copyState: MutableList> = ArrayList() for (sRow in state) { copyState.add(ArrayList(sRow)) } res.add(copyState) return } // 走訪所有列 for (col in 0..>?> { // 初始化 n*n 大小的棋盤,其中 'Q' 代表皇后,'#' 代表空位 val state: MutableList> = ArrayList() for (i in 0.. = ArrayList() for (j in 0..>?> = ArrayList() backtrack(0, n, state, res, cols, diags1, diags2) return res } /* Driver Code */ fun main() { val n = 4 val res: List?>?> = nQueens(n) println("輸入棋盤長寬為 $n") println("皇后放置方案共有 ${res.size} 種") for (state in res) { println("--------------------") for (row in state!!) { println(row) } } }