魔方阵 数组
魔方阵问题:就是给一个数N(N>2),然后将1 到 N*N填入N*N的矩阵中,使每行、每列的和是一个常数,例如:8 1 6
3 5 7
4 9 2
其实这是有公式的(分两大类,三小类),但是我不想使用公式,我想利用计算机的快速运算尝试最笨的方法,就是将这些数在每一位上试,我的方法很笨。下面是源码,和程序,我是人工输入的九个GOTO语句实现的,当N比较大时,不容易输入GOTO,所以请帮帮忙,谢谢。
Private Sub Form_Click()
Dim a(1 To 9) As Byte, p As Byte
For b = 1 To 9
a(1) = b
For c = 1 To 9
a(2) = c
If a(1) = a(2) Then GoTo c
For d = 1 To 9
a(3) = d
If a(3) = a(1) Or a(3) = a(2) Or a(1) + a(2) + a(3) <> 15 Then GoTo d
For e = 1 To 9
a(4) = e
For l = 1 To 3
If a(4) = a(l) Then GoTo e
Next
For f = 1 To 9
a(5) = f
For l = 1 To 4
If a(5) = a(l) Then GoTo f
Next
For g = 1 To 9
a(6) = g
For l = 1 To 5
If a(6) = a(l) Or a(4) + a(5) + a(6) <> 15 Then GoTo g
Next
For h = 1 To 9
a(7) = h
For l = 1 To 6
If a(7) = a(l) Or a(1) + a(4) + a(7) <> 15 Then GoTo h
Next
For i = 1 To 9
a(8) = i
For l = 1 To 7
If a(8) = a(l) Or a(2) + a(5) + a(8) <> 15 Then GoTo i
Next
For j = 1 To 9
a(9) = j
For l = 1 To 8
If a(9) = a(l) Or a(7) + a(8) + a(9) <> 15 Or a(3) + a(6) + a(9) <> 15 Then
GoTo j
Else
For m = 1 To 9
Text1.Text = Text1.Text & a(m)
If m Mod 3 = 0 Then Text1.Text = Text1.Text & vbCrLf
Next
p = p + 1
Text1.Text = Text1.Text & vbCrLf
Exit For
End If
Next
j:
Next
i:
Next
h:
Next
g:
Next
f:
Next
e:
Next
d:
Next
c:
Next
Next
MsgBox "一共有" & p & "组", vbOKOnly, "提示"
End Sub
魔方阵.rar
(1.4 KB)