n-皇后问题-dfs-按个枚举-golang
样例
package main
import (
"fmt"
)
var n int
var row, col, dg, udg []bool
var grid [][]string
func main() {
fmt.Scanf("%d", &n)
row, col, dg, udg = make([]bool, n*2), make([]bool, n*2), make([]bool, n*2), make([]bool, n*2)
grid = make([][]string, n)
for i := 0; i < n; i++ {
grid[i] = make([]string, n)
}
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
grid[i][j] = "."
}
}
dfs(0, 0, 0)
}
func dfs(x, y, s int) {
if y == n {
x++
y = 0
}
if x == n {
if s == n {
for i := 0; i < n; i++ {
for j := 0; j < n; j++ {
fmt.Printf("%s", grid[i][j])
}
fmt.Println()
}
fmt.Println()
}
return
}
if !row[x] && !col[y] && !dg[x+y] && !udg[y+n-x] {
grid[x][y] = "Q"
row[x] = true
col[y] = true
dg[x+y] = true
udg[y+n-x] = true
dfs(x, y+1, s+1)
row[x] = false
col[y] = false
dg[x+y] = false
udg[y+n-x] = false
grid[x][y] = "."
}
dfs(x, y+1, s)
}