输出螺旋矩阵(二)

输出这样的二维阵列:

1 3 4 10 11
2 5 9 12 19
6 8 13 18 20
7 14 17 21 24
15 16 22 23 25

Sub spiralmetrix(ByVal n As Integer)
n = n - 1
Dim i As Integer, j As Integer, a() As Integer
ReDim a(n, n)
a(0, 0) = 1
a(n, n) = (n + 1) ^ 2
For i = 1 To n
a(0, i) = a(0, i - 1) + IIf(i Mod 2 = 1, 2 * i, 1)
a(n, n - i) = (n + 1) ^ 2 + 1 - a(0, i)
a(i, 0) = a(i - 1, 0) + IIf(i Mod 2 = 1, 1, 2 * i)
a(n - i, n) = (n + 1) ^ 2 + 1 - a(i, 0)
Next


For i = 1 To n - 1
For j = 1 To n - 1
a(i, j) = a(i - 1, j + 1) + (-1) ^ (i - j)
Next
Next

Debug.Print "n=" & n + 1
For i = 0 To n
For j = 0 To n
Debug.Print Left(a(i, j) & Space(5), 5);
Next
Debug.Print
Next

End Sub

Private Sub Command1_Click()
Dim i As Integer
For i = 2 To 10
spiralmetrix i
Next
End Sub


输出:

n=2
1 3
2 4
n=3
1 3 4
2 5 8
6 7 9
n=4
1 3 4 10
2 5 9 11
6 8 12 15
7 13 14 16
n=5
1 3 4 10 11
2 5 9 12 19
6 8 13 18 20
7 14 17 21 24
15 16 22 23 25
n=6
1 3 4 10 11 21
2 5 9 12 20 22
6 8 13 19 23 30
7 14 18 24 29 31
15 17 25 28 32 35
16 26 27 33 34 36
n=7
1 3 4 10 11 21 22
2 5 9 12 20 23 34
6 8 13 19 24 33 35
7 14 18 25 32 36 43
15 17 26 31 37 42 44
16 27 30 38 41 45 48
28 29 39 40 46 47 49
n=8
1 3 4 10 11 21 22 36
2 5 9 12 20 23 35 37
6 8 13 19 24 34 38 49
7 14 18 25 33 39 48 50
15 17 26 32 40 47 51 58
16 27 31 41 46 52 57 59
28 30 42 45 53 56 60 63
29 43 44 54 55 61 62 64
n=9
1 3 4 10 11 21 22 36 37
2 5 9 12 20 23 35 38 53
6 8 13 19 24 34 39 52 54
7 14 18 25 33 40 51 55 66
15 17 26 32 41 50 56 65 67
16 27 31 42 49 57 64 68 75
28 30 43 48 58 63 69 74 76
29 44 47 59 62 70 73 77 80
45 46 60 61 71 72 78 79 81
n=10
1 3 4 10 11 21 22 36 37 55
2 5 9 12 20 23 35 38 54 56
6 8 13 19 24 34 39 53 57 72
7 14 18 25 33 40 52 58 71 73
15 17 26 32 41 51 59 70 74 85
16 27 31 42 50 60 69 75 84 86
28 30 43 49 61 68 76 83 87 94
29 44 48 62 67 77 82 88 93 95
45 47 63 66 78 81 89 92 96 99
46 64 65 79 80 90 91 97 98 100

你可能感兴趣的:(J#)