2012年11月20日 星期二

奇數階魔方陣

Problem Description


所謂的 n階魔方陣,就是把1到n 的這n 個 連續的正 整數填到一個 n×n的方陣中,使得每一列的和、每一行的和、以及兩個對角線的和都相等。請設計一個程式可以完成n為奇數的魔方陣。

Input

n (奇數) 

Output

奇數階魔方陣
Sample Input

請輸入 n: 5
Sample Output

17, 24, 01, 08, 15
23, 05, 07, 14, 16
04, 06, 13, 20, 22
10, 12, 19, 21, 03
11, 18, 25, 02, 09

2 則留言:

  1. Dim num(10, 10), basex, basey, orix, oriy As Integer
    Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Input #1, numm
    basex = 1: basey = Int(numm / 2) + 1
    For i = 1 To numm ^ 2
    num(basex, basey) = i
    orix = basex: basex = basex - 1
    If basex = 0 Then basex = numm
    oriy = basey: basey = basey + 1
    If basey = numm + 1 Then basey = 1
    If num(basex, basey) <> "" Then
    basex = orix + 1: basey = oriy
    End If
    Next
    For i = 1 To numm
    For ii = 1 To numm
    If num(i, ii) < 10 Then Print #2, "0" & num(i, ii) & " "; Else Print #2, num(i, ii) & " ";
    Next
    Print #2,
    Next
    Close #2
    Close #1
    End
    End Sub

    回覆刪除
  2. Dim a(), s, g, k, n As Integer
    Private Sub Form_Load()
    Me.Hide
    Open App.Path & "\in.txt" For Input As #1
    Open App.Path & "\out.txt" For Output As #2
    Input #1, n
    ReDim a(Val(n) + 1, Val(n) + 1)
    For i = 0 To UBound(a, 2)
    For j = 0 To UBound(a, 2)
    If i = 0 Or i = (Val(n) + 1) Or j = 0 Or j = (Val(n) + 1) Then a(i, j) = -1
    If i <> 0 And j <> 0 And i <> (Val(n) + 1) And j <> (Val(n) + 1) Then a(i, j) = 0
    Next j
    Next i
    s = 1: g = Val(n) \ 2 + 1: a(s, g) = 1
    s = s - 1: g = g + 1: k = 2
    Call y(s, g)
    For i = 1 To Val(n)
    For j = 1 To Val(n)
    If a(i, j) < 10 Then Print #2, "0" & a(i, j) & " "; Else Print #2, a(i, j) & " ";
    Next j
    Print #2,
    Next i
    Close #2
    Close #1
    End
    End Sub

    Sub y(s, g)
    If k > Val(n) * Val(n) Then Exit Sub
    If s = 0 And g = Val(n) + 1 Then s = s + 2: g = Val(n): a(s, g) = k: k = k + 1: Call y(s - 1, g + 1)
    If a(s, g) = -1 Then
    If g = Val(n) + 1 Then
    g = 1
    ElseIf s = 0 Then
    s = Val(n)
    ElseIf g = 0 Then
    g = Val(n)
    End If
    Call y(s, g)
    Else
    If a(s, g) = 0 Then
    a(s, g) = k: k = k + 1
    Call y(s - 1, g + 1)
    ElseIf a(s, g) = k - 1 Then
    s = s + 1: a(s, g) = k: k = k + 1
    Call y(s - 1, g + 1)
    Else
    s = s + 1: g = g - 1
    Call y(s, g)
    End If
    End If
    End Sub

    回覆刪除