【发布时间】:2026-01-17 17:40:01
【问题描述】:
八皇后谜题是将八皇后放在一个 8×8 棋盘上,这样两个皇后就不会互相威胁。因此,一个解决方案要求没有两个皇后共享相同的行、列或对角线。八皇后谜题是更一般的 n 皇后问题的一个示例,即在 n×n 棋盘上放置 n 个皇后,其中除了 n=2 或 n=3 之外,所有自然数 n 都有解。
但是,有没有人可以帮我解决这个递归方法中无限循环的问题?
ps:您可以复制/粘贴到 Playground 并尝试一下,谢谢!
class ChessBoard {
var limit: Int
var queens = [Queen]()
init(limit: Int) {
self.limit = limit
}
// Check if (i,j) is a safe position for queen
func isSafeForQueen(atRow row: Int, col: Int) -> Bool {
for q in queens {
// not in same row
if q.row == row { return false }
// not in same column
if q.col == col { return false }
// not in same diagol line
if abs(q.row-row) == abs(q.col-col) { return false }
}
return true
}
// recursive method
func dropQueen(atRow r: Int, c: Int) {
// running into last row
if r == limit {
if queens.count < 8 {
queens.removeLast()
let q = queens.last!
dropQueen(atRow: q.row, c: q.col+1)
}
output() // if success, log out the positions
return
}
// running into last column of current row
if c == limit {
queens.removeLast()
let q = queens.last!
// if no position for queen at current row, then back to last row
dropQueen(atRow: r-1, c: q.col+1)
}
// if this postion is safe for queen, then drop the queen and try next row; if not, try next spot
if isSafeForQueen(atRow: r, col: c) {
let q = Queen(row: r, col: c)
queens.append(q)
dropQueen(atRow: r+1, c: c)
} else {
dropQueen(atRow: r, c: c+1)
}
}
func play() {
dropQueen(atRow: 0, c: 0) // game will start at(0,0)
}
func output() -> String {
var s = ""
for q in queens {
s += "(\(q.row),\(q.col))"
}
return s
}
}
struct Queen {
var row: Int
var col: Int
}
// Tesing:
let b = ChessBoard(limit: 8)
//b.play()
【问题讨论】:
标签: swift recursion puzzle n-queens