Golang:
思路:八皇后问题拓展而来的N皇后问题,经典算法题这里就不做讲解了
func solveNQueens(n int) [][]string {
var res [][]string
chessboard:=make([]int,n)
placeQueen(&res,chessboard,n,0)
return res
}
func checkResult(chessboard []int,n int) bool {
for i:=0; i<n; i++ {
if chessboard[i]==chessboard[n]||math.Abs(float64(chessboard[i]-chessboard[n]))==float64(n-i){
return false
}
}
return true
}
func placeQueen(result *[][]string,chessboard []int,max int,temp int) {
if temp==max {
output(chessboard,result)
return
}
for i:=0; i<max; i++ {
chessboard[temp]=i
if checkResult(chessboard,temp) {
placeQueen(result,chessboard,max,temp+1)
}
}
}
func output(chessboard []int,result *[][]string) {
var tempRes []string
for _,v:=range chessboard{
ts:=""
for i:=0; i<len(chessboard); i++ {
if i==v{
ts=ts+"Q"
}else{
ts=ts+"."
}
}
tempRes = append(tempRes, ts)
}
*result=append(*result, tempRes)
}
有疑问加站长微信联系(非本文作者)