forked from spring1843/go-dsa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
n_queens.go
55 lines (49 loc) · 1.21 KB
/
n_queens.go
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
package backtracking
const (
empty = iota
queen
)
// Chessboard represents a chessboard.
type Chessboard [][]int
// NQueens solves the problem in O(n!) time and O(n) space.
func NQueens(n int) []Chessboard {
output := nQueensRecursive(0, n, make([]int, n), make(Chessboard, 0))
return toPrettyChessboard(output, n)
}
func nQueensRecursive(row, n int, cols []int, output Chessboard) Chessboard {
if n == 0 {
return output
}
if row == n {
output = append(output, append([]int{}, cols...))
return output
}
for col := 0; col < n; col++ {
if isValidQueenPlacement(row, col, cols) {
cols[row] = col
output = nQueensRecursive(row+1, n, cols, output)
}
}
return output
}
func isValidQueenPlacement(row, col int, cols []int) bool {
for i := 0; i < row; i++ {
if col == cols[i] || col-row == cols[i]-i || col+row == cols[i]+i {
return false
}
}
return true
}
func toPrettyChessboard(solutions Chessboard, n int) []Chessboard {
chessboards := make([]Chessboard, len(solutions))
for i, row := range solutions {
chessBoard := make(Chessboard, n)
for j, col := range row {
newRow := make([]int, n)
newRow[col] = queen
chessBoard[j] = newRow
}
chessboards[i] = chessBoard
}
return chessboards
}