Sub 回溯算法_N皇后()
n = 8
ReDim ar(n)
cnt = nqueen(n, 0, ar, 0)
Debug.Print (cnt)
End Sub
Public Function nqueen(n, row, res, count)
If row = n Then count = count + 1: nqueen = count
For col = 0 To n - 1
res(row) = col
If isOk(row, col, res) Then count = nqueen(n, row + 1, res, count)
Next
nqueen = count
End Function
Private Function isOk(row, col, res) As Boolean
For i = 0 To row - 1
If res(i) = col Then isOk = False: Exit Function
If row - i = col - res(i) Or row - i = res(i) - col Then isOk = False: Exit Function
Next
isOk = True
End Function