8 1 6
3 5 7
4 9 2
上面的矩陣中直排橫列對角線的總和都是15
17 24 1 8 15
23 5 7 14 16
4 6 13 20 22
10 12 19 21 3
11 18 25 2 9
上面的矩陣中直排橫列對角線的總和都是65
輸入說明:
輸入一數 n (0<n<10000,且n mod 2 =1)
輸出說明:
請照題目規則,輸出n行n列的矩陣,且直行橫列對角線總和都要相等。
輸入範例:
7
輸出範例:
30 39 48 1 10 19 28
38 47 7 9 18 27 29
46 6 8 17 26 35 37
5 14 16 25 34 36 45
13 15 24 33 42 44 4
21 23 32 41 43 3 12
22 31 40 49 2 11 20
Dim Ans, Final As Integer, x, y, n
回覆刪除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 Ans(n, n)
Final = n ^ 2
x = 1: y = (n + 1) / 2
For i = 1 To Final
Ans(x, y) = i
If check(x, y) = True Then Call Up(x, y) Else Call nUp(x, y)
Next
For i = 1 To n
For j = 1 To n
Print #2, Ans(i, j),
Next
Print #2, ""
Next
Close
Close
End
End Sub
Function check(ByVal a, ByVal b)
Call Up(a, b)
If Ans(a, b) <> 0 Then check = False Else check = True
End Function
Function Up(a, b)
If (a - 1) > 0 Then a = a - 1 Else a = n
If (b + 1) <= n Then b = b + 1 Else b = 1
End Function
Function nUp(a, b)
If (a + 1) <= n Then a = a + 1 Else a = 1
End Function
有規則後簡單了很多
數字大時似乎不只一種答案
回覆刪除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(N, N) As Integer
X = 1
Y = (1 + N) / 2
A(X, Y) = 1
For i = 2 To N ^ 2
RX = X + 2: If RX > N Then RX = RX - N
RY = Y + 1: If RY > N Then RY = RY - N
If A(RX, RY) = 0 Then
X = RX
Y = RY
A(X, Y) = i
Else
X = X + 1: If X > N Then X = X - N
A(X, Y) = i
End If
Next i
For i = 1 To N
For j = 1 To N
Print #2, A(i, j),
Next j
Print #2,
Next i
Close #2
Close #1
End
End Sub
out.txt
46 31 16 1 42 27 12
5 39 24 9 43 35 20
13 47 32 17 2 36 28
21 6 40 25 10 44 29
22 14 48 33 18 3 37
30 15 7 41 26 11 45
38 23 8 49 34 19 4
加起來也是175
回覆刪除5*5
回覆刪除我的答案是
23 12 1 20 9
4 18 7 21 15
10 24 13 2 16
11 5 19 8 22
17 6 25 14 3
我是用老師給的方法
回覆刪除用N進位的方式去填數字