NQueens
This commit is contained in:
parent
87429c84b4
commit
369ae717d1
77
scala/src/main/scala/ch39_back_tracking/NQueens.scala
Normal file
77
scala/src/main/scala/ch39_back_tracking/NQueens.scala
Normal file
@ -0,0 +1,77 @@
|
||||
package ch39_back_tracking
|
||||
|
||||
import scala.util.control.Breaks.{break, breakable}
|
||||
|
||||
class NQueens(numberOfQueens:Int) {
|
||||
//use array index to identify the row,the value of the row to identify the column
|
||||
val result = new Array[Int](numberOfQueens)
|
||||
var count = 0
|
||||
|
||||
def calcNQueues(row: Int): Unit = {
|
||||
if (row == numberOfQueens) {
|
||||
//everything is done
|
||||
printNQueens()
|
||||
return
|
||||
}
|
||||
|
||||
for (column <- Range(0, numberOfQueens)) {
|
||||
if (isOkOnColumn(row, column)) {
|
||||
result(row) = column //place the column value into the array
|
||||
calcNQueues(row + 1) //calculate next row
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
def isOkOnColumn(row: Int, column: Int): Boolean = {
|
||||
var ok = true
|
||||
var leftUp = column - 1
|
||||
var rightUp = column + 1
|
||||
|
||||
breakable {
|
||||
//will compare all the rows above current row
|
||||
for (i <- row - 1 to 0 by -1) {
|
||||
//check current column
|
||||
if (result(i) == column) {
|
||||
ok = false
|
||||
break
|
||||
}
|
||||
//check left up
|
||||
if (leftUp >= 0) {
|
||||
if (result(i) == leftUp) {
|
||||
ok = false
|
||||
break
|
||||
}
|
||||
}
|
||||
//check right up
|
||||
if (rightUp < numberOfQueens) {
|
||||
if (result(i) == rightUp) {
|
||||
ok = false
|
||||
break
|
||||
}
|
||||
}
|
||||
//move leftUp and rightUp
|
||||
leftUp -= 1
|
||||
rightUp += 1
|
||||
}
|
||||
}
|
||||
|
||||
ok
|
||||
}
|
||||
|
||||
def printNQueens(): Unit = {
|
||||
count +=1
|
||||
for (row <- Range(0, numberOfQueens)) {
|
||||
for (column <- Range(0, numberOfQueens)) {
|
||||
if (result(row) == column) {
|
||||
print("Q ")
|
||||
} else {
|
||||
print("* ")
|
||||
}
|
||||
}
|
||||
//new line for next row
|
||||
println("")
|
||||
}
|
||||
println(count+"==============")
|
||||
}
|
||||
}
|
21
scala/src/test/scala/ch39_back_tracking/NQueensTest.scala
Normal file
21
scala/src/test/scala/ch39_back_tracking/NQueensTest.scala
Normal file
@ -0,0 +1,21 @@
|
||||
package ch39_back_tracking
|
||||
|
||||
import org.scalatest.FlatSpec
|
||||
|
||||
class NQueensTest extends FlatSpec {
|
||||
|
||||
behavior of "NQueensTest"
|
||||
|
||||
it should "calc8Queues" in {
|
||||
val eightQueens = new NQueens(8)
|
||||
eightQueens.calcNQueues(0)
|
||||
|
||||
}
|
||||
|
||||
it should "calc4Queues" in {
|
||||
val eightQueens = new NQueens(4)
|
||||
eightQueens.calcNQueues(0)
|
||||
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user