This repository was archived by the owner on Jul 6, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEightQueens.scala
80 lines (71 loc) · 1.63 KB
/
EightQueens.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
object EightQueens {
def main(args: Array[String]): Unit = {
solveQueens(8)
}
def solveQueens(n: Int): Unit = {
val board = Array.ofDim[Boolean](n, n)
if (placeQueens(board, 0, n)) {
println(s"Solution found for ${n} queens:")
printBoard(board)
} else {
println(s"No solution found for ${n} queens.")
}
}
def placeQueens(board: Array[Array[Boolean]], col: Int, n: Int): Boolean = {
if (col >= n) {
true
} else {
var placed = false
var row = 0
while (row < n && !placed) {
if (isSafe(board, row, col, n)) {
board(row)(col) = true
placed = placeQueens(board, col + 1, n)
if (!placed) {
board(row)(col) = false // backtrack
}
}
row += 1
}
placed
}
}
def isSafe(board: Array[Array[Boolean]], row: Int, col: Int, n: Int): Boolean = {
// Check if no two queens share the same column
for (i <- 0 until col) {
if (board(row)(i)) {
return false
}
}
// Check upper diagonal on left side
var i = row
var j = col
while (i >= 0 && j >= 0) {
if (board(i)(j)) {
return false
}
i -= 1
j -= 1
}
// Check lower diagonal on left side
i = row
j = col
while (i < n && j >= 0) {
if (board(i)(j)) {
return false
}
i += 1
j -= 1
}
true
}
def printBoard(board: Array[Array[Boolean]]): Unit = {
val n = board.length
for (i <- 0 until n) {
for (j <- 0 until n) {
if (board(i)(j)) print("Q ") else print(". ")
}
println()
}
}
}