Imports System.Math
Public Class eightqueen
Dim topnum As Int16 = 7
Dim printb As Boolean
Dim j2 As Int16 = 0
Dim eightqueenplace2((topnum * 2) * (topnum * 2), topnum, topnum) As Int16
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim eightqueenplace1(topnum, topnum) As Int16
For i = 0 To topnum
For j = 0 To topnum
eightqueenplace1(i, j) = 1 '初始化
Next
Next
bu(eightqueenplace1, 0, 0, 0)
TextBox1.Text = TextBox1.Text + Chr(13) + Chr(10) + j2.ToString + "end" '输出总种数和和结束标志
End Sub
Private Function check(ByRef eightqueenplace1(,) As Int16, ByVal ii As Int16, ByRef jj As Int16)
Dim x, y As Int16
For i = 0 To topnum
For j = 0 To topnum
If eightqueenplace1(i, j) = 2 Then
x = 0
y = 0
x = i - ii
y = j - jj
If Abs(x) = Abs(y) Or Abs(x) = 0 Or Abs(y) = 0 Then
Return 1
Exit For
End If
End If
Next
Next
Return 2
End Function
Private Sub print(ByRef eightqueenplace1(,) As Int16) '输出符合条件的排列
For ii = 0 To topnum
For jj = 0 To topnum
TextBox1.Text = TextBox1.Text + " " + eightqueenplace1(ii, jj).ToString
Next
TextBox1.Text = TextBox1.Text + Chr(13) + Chr(10)
Next
TextBox1.Text = TextBox1.Text + Chr(13) + Chr(10)
End Sub
Private Sub bu(ByVal eightqueenplace1(,) As Int16, ByVal ii As Int16, ByRef jj As Int16, ByVal numm As Int16) '递归
Dim eightqueenplace(topnum, topnum) As Int16
Dim i As Int16
Dim j1 As Int16
j1 = jj
For i = 0 To topnum
For j = 0 To topnum
eightqueenplace(i, j) = eightqueenplace1(i, j)
Next
Next
For i = ii To topnum
For j = j1 To topnum
If check(eightqueenplace, i, j) = 2 Then
If j<>topnum then
eightqueenplace(i, j) = 1
bu(eightqueenplace, i, j + 1, numm) '能放但不放的分支
End If
numm = numm + 1
eightqueenplace(i, j) = 2
bu(eightqueenplace, i, j + 1, numm) '能放就放的分支
End If
Next
j1 = 0
Next
If i = topnum + 1 And numm > 7 And jj <> numm + 1 Then '判断是否符合条件
If j2 > (topnum * 2) * (topnum * 2) Then Exit Sub
For j = 0 To (topnum * 2) * (topnum * 2) '判断是否已经输出过
printb = True
For a1 = 0 To topnum
For a2 = 0 To topnum
If eightqueenplace2(j, a1, a2) <> eightqueenplace(a1, a2) Then
GoTo gggg
End If
Next
Next
printb = False
Exit For
gggg:
Next
If printb = True Then '没有输出过,记录下来
For a1 = 0 To topnum
For a2 = 0 To topnum
eightqueenplace2(j2, a1, a2) = eightqueenplace(a1, a2)
Next
Next
Call print(eightqueenplace)
j2 = j2 + 1
End If
End If
End Sub
End Class