80 lines
No EOL
2.2 KiB
Swift
80 lines
No EOL
2.2 KiB
Swift
//
|
|
// main.swift
|
|
// EightQueens
|
|
//
|
|
// Created by Donald Burr on 5/27/15.
|
|
// Copyright (c) 2015 Donald Burr. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
var solutionsFound = 0
|
|
var positionsChecked = 0
|
|
|
|
// create 8 queen objects, place them one per row
|
|
let myQueens = map(0...7) { Queen(forRow: $0) }
|
|
|
|
func isSafe(currentRow: Int, currentColumn: Int) -> Bool {
|
|
positionsChecked++
|
|
|
|
// iterate over all queens in previous rows
|
|
for previousRow in 0..<currentRow {
|
|
// check vertical: are we trying to place in the same column as a previously placed queen?
|
|
if myQueens[previousRow].column == currentColumn {
|
|
return false
|
|
}
|
|
// check diagonal
|
|
let differenceInRows = currentRow - previousRow
|
|
let differenceInColumns = currentColumn - myQueens[previousRow].column
|
|
if (differenceInRows == differenceInColumns || differenceInRows == -differenceInColumns) {
|
|
return false
|
|
}
|
|
}
|
|
|
|
// compared all previous queens, no conflict
|
|
myQueens[currentRow].column = currentColumn
|
|
return true
|
|
}
|
|
|
|
func moveQueenAcrossRow(row: Int) {
|
|
for column in 0...7 {
|
|
// move queen column by column, checking if it's safe
|
|
if isSafe(row, column) {
|
|
// if we just placed the 8th queen, we have a result!
|
|
if row == 7 {
|
|
solutionsFound++
|
|
printAnswer()
|
|
} else {
|
|
// recursive call - now move the queen to the NEXT row
|
|
moveQueenAcrossRow(row+1)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func printAnswer() {
|
|
println("SOLUTION #\(solutionsFound)")
|
|
println()
|
|
|
|
// go backwards to print from top down
|
|
for currentRow in reverse(0...7) {
|
|
// print row number (using chess numbering)
|
|
print(currentRow+1)
|
|
for currentColumn in 0...7 {
|
|
if (myQueens[currentRow].column == currentColumn) {
|
|
print(" Q ")
|
|
} else {
|
|
print(" . ")
|
|
}
|
|
}
|
|
println()
|
|
}
|
|
println(" A B C D E F G H ")
|
|
println()
|
|
}
|
|
|
|
// start by trying to move queen across row 0
|
|
moveQueenAcrossRow(0)
|
|
|
|
// that's it
|
|
println("POSITIONS CHECKED: \(positionsChecked)") |