Skip to content

Instantly share code, notes, and snippets.

@martintrojer
Created June 1, 2013 12:19
Show Gist options
  • Save martintrojer/5690189 to your computer and use it in GitHub Desktop.
Save martintrojer/5690189 to your computer and use it in GitHub Desktop.
Queens
object queens extends App {
def queens(n: Int): List[List[(Int, Int)]] = {
def placeQueens(k: Int): List[List[(Int, Int)]] = {
if (k == 0)
List(List())
else for {
queens <- placeQueens(k - 1)
col <- 1 to n
queen = (k, col)
if queens forall (q => !inCheck(queen, q))
} yield queen :: queens
}
placeQueens(n)
}
def inCheck(q1: (Int, Int), q2: (Int, Int)) =
q1._1 == q2._1 ||
q1._2 == q2._2 ||
(q1._1 - q2._1).abs == (q1._2 - q2._2).abs
println(for (n <- 1 to 10) yield queens(n).length)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment