タスクは、N個のクイーンをNxNボードに配置するソリューションの数を数えることです。パフォーマンスを向上させるために考えられるすべてのケースを考えようとしましたが、N=15で実行するにはほぼ50秒かかります。これが私が行ったことです。
Dim resultCount As Integer = 0
Dim fieldSize As Integer = 0
Dim queenCount As Integer = 0
Dim availableCols As Boolean()
Dim availableLeftDiagonal As Boolean()
Dim availableRightDiagonal As Boolean()
Private Sub butCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles butCalc.Click
Dim currentTime As Long = Now.Ticks
'Reset old result
resultCount = 0
fieldSize = CInt(txtFieldSize.Text)
queenCount = 0
ReDim availableCols(fieldSize - 1)
For i As Integer = 0 To fieldSize - 1
availableCols(i) = True
Next
ReDim availableLeftDiagonal((fieldSize - 1) * 2)
For i As Integer = 0 To (fieldSize - 1) * 2
availableLeftDiagonal(i) = True
Next
ReDim availableRightDiagonal((fieldSize - 1) * 2)
For i As Integer = 0 To (fieldSize - 1) * 2
availableRightDiagonal(i) = True
Next
'Calculate
For x As Integer = 0 To fieldSize - 1
putQueen(x, 0)
Next
'Print result
txtResult.Text = "Found " & resultCount & " in " & (Now.Ticks - currentTime) / 10000 & " miliseconds."
End Sub
Private Sub putQueen(ByVal pX As Integer, ByVal pY As Integer)
'Put in result
availableCols(pX) = False
availableLeftDiagonal(pX + pY) = False
availableRightDiagonal(pX - pY + (fieldSize - 1)) = False
queenCount += 1
'Recursion
If (queenCount = fieldSize) Then
resultCount += 1
Else
pY += 1 'pY = next row
For x As Integer = 0 To fieldSize - 1
If (availableCols(x) AndAlso
availableLeftDiagonal(x + pY) AndAlso
availableRightDiagonal(x - pY + (fieldSize - 1))) Then putQueen(x, pY)
Next
pY -= 1 'Reset pY
End If
'Roll up result
availableCols(pX) = True
availableLeftDiagonal(pX + pY) = True
availableRightDiagonal(pX - pY + (fieldSize - 1)) = True
queenCount -= 1
End Sub
可能かどうか教えてください(私の先生は正確な時間を教えてくれなかったので、「許容時間」とだけ言っています。可能であれば、方法を教えてください。または、手がかりを教えてください。