n-皇后问题-dfs-golang
blablabla
golang
package main
import "fmt"
var n int
var grid [][]string //棋盘
var cor, dg, udg []bool //列,两条对角线
func main(){
fmt.Scanf("%d", &n)
grid = make([][]string, n)
for i := 0; i < n; i ++{
grid[i] = make([]string, n)
}
cor, dg, udg = make([]bool, n), make([]bool, n*2), make([]bool, n*2)
//棋盘
for i := 0; i < n; i++{
for j:= 0; j < n; j++{
grid[i][j] = "."
}
}
dfs(0)
}
func dfs(r int){
if r == n{
for i := 0; i < n; i++{
for j:= 0; j < n; j++{
fmt.Printf("%s", grid[i][j])
}
fmt.Println()
}
fmt.Println()
}
for i := 0; i < n; i++{
if !cor[i] && !dg[r+i] && !udg[r+n-i]{
grid[r][i] = "Q"
cor[i] = true
dg[r+i] = true
udg[r+n-i] = true
dfs(r+1)
grid[r][i] = "."
cor[i] = false
dg[r+i] = false
udg[r+n-i] = false
}
}
}