Created
April 18, 2012 21:45
-
-
Save jklmli/2416824 to your computer and use it in GitHub Desktop.
Scala bible's implementation of an N-Queens solver.
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 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) | |
column <- 1 to n | |
queen = (k, column) | |
if isSafe(queen, queens) | |
} yield queen :: queens | |
placeQueens(n) | |
} | |
def isSafe(queen: (Int, Int), queens: List[(Int, Int)]) = | |
queens forall (q => !inCheck(queen, q)) | |
def inCheck(q1: (Int, Int), q2: (Int, Int)) = | |
q1._1 == q2._1 || // same row | |
q1._2 == q2._2 || // same column | |
(q1._1 - q2._1).abs == (q1._2 - q2._2).abs // on diagonal |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment