Skip to content

Instantly share code, notes, and snippets.

@piyushchauhan2011
Forked from pathikrit/NQueen.scala
Created April 11, 2016 11:10
Show Gist options
  • Save piyushchauhan2011/8d3996383f9cc643199dadeaa8e2ae52 to your computer and use it in GitHub Desktop.
Save piyushchauhan2011/8d3996383f9cc643199dadeaa8e2ae52 to your computer and use it in GitHub Desktop.
O(n!) solution to the n-Queen puzzle (https://en.wikipedia.org/wiki/Eight_queens_puzzle)
def nQueens(n: Int) = (0 until n).permutations filter {col => // col[r] = column of queen on r-th row
val p = col.zipWithIndex.toSet // col[] must be a permutation of (0 until n) because of rook attacks
p.map{case (c, d) => c + d}.size == n && // No 2 queens can have same col + diag because of left-bishop attacks
p.map{case (c, d) => c - d}.size == n // No 2 queens can have same col - diag because of right-bishop attacks
}
/*************************************** [Printing code below] *************************************************/
for ((solution, num) <- nQueens(8).zipWithIndex) {
println(s"Solution #${num + 1}:")
solution foreach {col =>
val row = solution.indices.map(i => if (i == col) 'Q' else '-')
println(row.mkString)
}
}
// Feel free to run this code on http://scalafiddle.net
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment