Skip to content

Instantly share code, notes, and snippets.

@takaki
Created July 19, 2016 07:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takaki/5771455167463468452a6396a5ccbdf7 to your computer and use it in GitHub Desktop.
Save takaki/5771455167463468452a6396a5ccbdf7 to your computer and use it in GitHub Desktop.
object EightQueens {
def queen(n: Int): List[List[Int]] = n match {
case 0 => List(List())
case `n` => for {b <- queen(n - 1); q <- 0 to 7 if safe(q, b)} yield q :: b
}
def safe(q: Int, b: List[Int]) = b.indices.forall(i => checks(q, b, i))
def checks(q: Int, b: List[Int], i: Int) = q != b(i) && (Math.abs(q - b(i)) != i + 1)
def main(args: Array[String]) {
val res = queen(8)
res.foreach(l => println(l))
println(res.length)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment