有一個問題老是困惑著我,這就是一個很有名的問題魔方陣.有沒有辦法能輸出在變量i範圍內,所有能組成n*n階的魔方陣.或者是有好的算法呢.

解决方案 »

  1.   

    Private Sub Command1_Click()
     Dim input_i As Integer
     Dim i As Integer
     Dim n As Integer
     Dim r As Integer
     Dim c As Integer
     Dim m() As Integer
     Dim num As Integer
     Dim row As Integer
     Dim col As Integer
     input_i = InputBox("输入i")
     If input_i < 1 Then
         MsgBox "输入大于等于1的数"
     End If
     For n = 1 To input_i Step 2
      num = n * n
      ReDim m(n - 1, n - 1)
      row = 0
      col = (n - 1) / 2
      i = 1
      Do While (i <= num)
        If (row = -1) Then row = n - 1
        If (col = n) Then col = 0
        m(row, col) = i
        If (i Mod n) = 0 Then
          row = row + 1
         Else
          row = row - 1
          col = col + 1
        End If
         i = i + 1
     Loop
     Print
     Print "下面输入的是n="; n & "阶"
     For r = 0 To n - 1
       For c = 0 To n - 1
        Print Tab(c * 6); m(r, c);
       Next c
     Next r
     Next n
    End Sub