-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0051-n-queens.go
More file actions
55 lines (42 loc) · 1.01 KB
/
Copy path0051-n-queens.go
File metadata and controls
55 lines (42 loc) · 1.01 KB
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
// https://leetcode.com/problems/n-queens/
func solveNQueens(n int) [][]string {
solutions := make([][]string, 0)
board := make([][]byte, n)
for row := range board {
board[row] = make([]byte, n)
for col := range board[row] {
board[row][col] = '.'
}
}
cols := make([]bool, n) // (row)
negDiag := make([]bool, 2*n) // (row - col)
posDiag := make([]bool, 2*n) // (row + col)
var backtrack func(row int)
backtrack = func(row int) {
if row == n {
solution := make([]string, n)
for idx := range solution {
solution[idx] = string(board[idx])
}
solutions = append(solutions, solution)
return
}
for col := range n {
if cols[col] || negDiag[n-row+col] || posDiag[row+col] {
continue
}
board[row][col] = 'Q'
cols[col] = true
negDiag[n-row+col] = true
posDiag[row+col] = true
backtrack(row + 1)
board[row][col] = '.'
cols[col] = false
negDiag[n-row+col] = false
posDiag[row+col] = false
}
}
backtrack(0)
return solutions
}