-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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