create an 8 8 int array to represent a chess board and writ
create an 8 × 8 int[][] array to represent a chess board and write a recursive method which solves the eight queens problem. The goal is to find one state where eight queens are placed on a chess board where no queens can attack one another. Netbeans source code, Please explain the code to get a better understanding.
Solution
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()![create an 8 × 8 int[][] array to represent a chess board and write a recursive method which solves the eight queens problem. The goal is to find one state where create an 8 × 8 int[][] array to represent a chess board and write a recursive method which solves the eight queens problem. The goal is to find one state where](/WebImages/12/create-an-8-8-int-array-to-represent-a-chess-board-and-writ-1011943-1761522472-0.webp)