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