Exercise10.1.1 Write the function isSafe.
This file contains 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
object NQueensProblem { | |
def queens(n: Int): List[List[Int]] = { | |
def placeQueens(k: Int): List[List[Int]] = | |
if (k == 0) List(List()) | |
else for { queens <- placeQueens(k - 1) | |
column <- List.range(1, n + 1) | |
if isSafe(column, queens, 1)} yield column :: queens | |
placeQueens(n) | |
} | |
def isSafe(col: Int, queens: List[Int], delta: Int): Boolean = queens match { | |
case Nil => true | |
case x :: xs => col != x && col != x - delta && col != x + delta && | |
isSafe(col, xs, delta + 1) | |
} | |
def main(args: Array[String]) { | |
println ("Solving nqueens: ") | |
val x = queens(8) | |
println("Number of solutions: " + x.length) | |
println(x) | |
} | |
} |
No comments:
Post a Comment