Advertisement
jules0707

nQueens

Feb 27th, 2017
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.89 KB | None | 0 0
  1. package week6
  2. import math._
  3.  
  4. object nQueens {
  5.  
  6.   def queens(n: Int): Set[List[Int]] = {
  7.  
  8.     def placeQueens(k: Int): Set[List[Int]] =
  9.       if (k == 0) Set(List())
  10.       else
  11.         for {
  12.           queens <- placeQueens(k - 1)
  13.           col <- 0 until n
  14.           if isSafe(col, queens)
  15.         } yield col :: queens
  16.     placeQueens(n)
  17.   }                                               //> queens: (n: Int)Set[List[Int]]
  18.  
  19.   def isSafe(col: Int, queens: List[Int]): Boolean = {
  20.     val row = queens.length
  21.     val queensWithRow = (row - 1 to 0 by -1) zip queens
  22.     queensWithRow forall {
  23.       case (r, c) => (col != c) && (math.abs(col-c) != row - r)
  24.     }
  25.   }                                               //> isSafe: (col: Int, queens: List[Int])Boolean
  26.  
  27.  
  28. queens(4)                                         //> res0: Set[List[Int]] = Set(List(1, 3, 0, 2), List(2, 0, 3, 1))
  29.  
  30.  
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement