-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path51.n-皇后.go
75 lines (69 loc) · 1.31 KB
/
51.n-皇后.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
/*
* @lc app=leetcode.cn id=51 lang=golang
*
* [51] N 皇后
*/
// @lc code=start
/**
* 回溯
*/
func isValid(board []string, row, col int) bool {
rules := [8][2]int{
[2]int{0, 1}, // right
[2]int{0, -1}, // left
[2]int{1, 0}, // bottom
[2]int{-1, 0}, // top
[2]int{-1, 1}, // top right
[2]int{1, -1}, // bottom left
[2]int{-1, -1}, // top left
[2]int{1, 1}, // bottom right
}
size := len(board)
// check rows
for _, rule := range rules {
r, c := rule[0], rule[1]
px, py := row+r, col+c
for px < size && py < size && px > -1 && py > -1 {
if board[px][py] == 'Q' {
return false
}
px += r
py += c
}
}
return true
}
func solveNQueens(n int) [][]string {
ans := [][]string{}
board := make([]string, n)
for i := 0; i < n; i++ {
bytes := make([]byte, n)
for j := 0; j < len(bytes); j++ {
bytes[j] = '.'
}
board[i] = string(bytes)
}
var recursion func(row, col int)
recursion = func(row, col int) {
if row == n {
comb := make([]string, n)
copy(comb, board)
ans = append(ans, comb)
return
}
for col < n {
if isValid(board, row, col) {
old := board[row]
temp := []byte(old)
temp[col] = 'Q'
board[row] = string(temp)
recursion(row+1, 0)
board[row] = old
}
col++
}
}
recursion(0, 0)
return ans
}
// @lc code=end