/
eight_queen.go
145 lines (126 loc) · 2.39 KB
/
eight_queen.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
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package main
import (
"fmt"
)
func IsPositionOK(result [][]int, xPos int, yPos int) bool {
for i := 0; i < xPos; i++ {
y := GetYPosition(result, i)
if y == yPos || i+y == xPos+yPos || i+yPos == y+xPos {
return false
}
}
return true
}
func GetYPosition(result [][]int, xPos int) (y int) {
for yPos := 0; yPos < 8; yPos++ {
if result[xPos][yPos] == 1 {
return yPos
}
}
return -1
}
func EightQueen() ([][]int, bool) {
foundResult := true
result := make([][]int, 8)
for i := 0; i < 8; i++ {
result[i] = make([]int, 8)
}
for x := 0; x < 8; {
yPos := GetYPosition(result, x)
if yPos != -1 {
result[x][yPos] = 0
yPos += 1
} else {
yPos = 0
}
if yPos == 8 {
x--
} else {
for y := yPos; y < 8; y++ {
if IsPositionOK(result, x, y) {
result[x][y] = 1
x++
break
} else {
if y == 7 {
x--
}
}
}
}
if x < 0 {
foundResult = false
break
}
}
return result, foundResult
}
func Recursion(result [][]int, x int) {
if x < 0 || x > 7 {
return
}
yPos := GetYPosition(result, x)
if yPos != -1 {
result[x][yPos] = 0
yPos += 1
} else {
yPos = 0
}
if yPos == 8 {
Recursion(result, x-1)
}
for y := yPos; y < 8; y++ {
if IsPositionOK(result, x, y) {
result[x][y] = 1
Recursion(result, x+1)
break
} else {
if y == 7 {
Recursion(result, x-1)
}
}
}
}
func EightQueenRecursion() ([][]int, bool) {
foundResult := true
result := make([][]int, 8)
for i := 0; i < 8; i++ {
result[i] = make([]int, 8)
}
Recursion(result, 0)
return result, foundResult
}
func main() {
fmt.Println("Welcome to the playground!")
fmt.Println("Eight queen normal loop solution result:")
if result, ok := EightQueen(); ok {
for i := 0; i < len(result); i++ {
fmt.Println(result[i])
}
}
fmt.Println("Eight queen recursion solution result:")
if result2, ok := EightQueenRecursion(); ok {
for i := 0; i < len(result2); i++ {
fmt.Println(result2[i])
}
}
}
// Welcome to the playground!
// Eight queen normal loop solution result:
// [1 0 0 0 0 0 0 0]
// [0 0 0 0 1 0 0 0]
// [0 0 0 0 0 0 0 1]
// [0 0 0 0 0 1 0 0]
// [0 0 1 0 0 0 0 0]
// [0 0 0 0 0 0 1 0]
// [0 1 0 0 0 0 0 0]
// [0 0 0 1 0 0 0 0]
// Eight queen recursion solution result:
// [1 0 0 0 0 0 0 0]
// [0 0 0 0 1 0 0 0]
// [0 0 0 0 0 0 0 1]
// [0 0 0 0 0 1 0 0]
// [0 0 1 0 0 0 0 0]
// [0 0 0 0 0 0 1 0]
// [0 1 0 0 0 0 0 0]
// [0 0 0 1 0 0 0 0]