object EightQueen2 extends App{
val pos = new Array[Int](8)
val rowvisited = new Array[Boolean](8)
val colvisited = new Array[Boolean](8)
val maindiagonalvisited = new Array[Boolean](15)
val counterdiagonalvisited = new Array[Boolean](15)
var num = 0
def printqueen(){
for(i <- 0.until(8);j <- 0.until(8)){
if(j == pos(i)) print('*') else print('-')
if(j == 7) println()
}
}
def dfs(x:Int,count:Int){
if(count == 8){
num += 1
println(num)
printqueen()
return
}
if(x >= 8) return
dfs(x+1,count)
for(y <- 0.until(8)){
if(!rowvisited(x) && !colvisited(y) && !maindiagonalvisited(x+y) && !counterdiagonalvisited(x-y+7)){
rowvisited(x) = true
colvisited(y) = true
pos(x) = y
maindiagonalvisited(x+y) = true
counterdiagonalvisited(x-y+7) = true
dfs(x+1,count+1)
rowvisited(x) = false
colvisited(y) = false
pos(x) = 0
maindiagonalvisited(x+y) = false
counterdiagonalvisited(x-y+7) = false
}
}
}
dfs(0,0)
}
scala 深搜法解决八皇后问题
最新推荐文章于 2021-09-23 16:31:59 发布