-
Notifications
You must be signed in to change notification settings - Fork 24
/
leetcode0051.go
65 lines (53 loc) · 1.11 KB
/
leetcode0051.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
/*
LeetCode 51: https://leetcode.com/problems/n-queens/
*/
package leetcode
import (
"math"
)
func solveNQueens(n int) [][]string {
nums := make([]int, n)
for i := 0; i < len(nums); i++ {
nums[i] = i
}
return helper51(nums, 0, make([][]string, 0))
}
func isValidBoard(nums []int, last int) bool {
for i := 0; i <= last; i++ {
for j := i + 1; j <= last; j++ {
if j-i == int(math.Abs(float64(nums[i]-nums[j]))) {
return false
}
}
}
return true
}
func generateBoard(nums []int) []string {
result := make([]string, 0)
for _, num := range nums {
var str string
for i := 0; i < len(nums); i++ {
if i == num {
str = str + "Q"
} else {
str = str + "."
}
}
result = append(result, str)
}
return result
}
func helper51(nums []int, i int, result [][]string) [][]string {
if i == len(nums) {
result = append(result, generateBoard(nums))
} else if i < len(nums) {
for j := i; j < len(nums); j++ {
nums[i], nums[j] = nums[j], nums[i]
if isValidBoard(nums, i) {
result = helper51(nums, i+1, result)
}
nums[i], nums[j] = nums[j], nums[i]
}
}
return result
}