输出这样的二维阵列:
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
分析:
填充如此一个n*n阵列 ,先观察规律:
n=1
1
n=2
1 2
4 3
对于n*n阵列,可以先将1-4*n 填充四周,内部用一个(n-2)*(n-2) 的阵列加上4*(n-1)填充,
所以用递归比较直观,代码如下:
Private Sub Command1_Click()
Dim result() As Long, i As Long, maxlen As Long
For i = 1 To 18
maxlen = Len(CStr(i * i)) + 1
spiral i, result
For j = 0 To i ^ 2 - 1
If j Mod i = 0 Then Debug.Print
Debug.Print Right(Space(maxlen) & result(j), maxlen);
Next
Debug.Print
Next
End Sub
Sub spiral(ByVal n As Integer, ByRef result() As Long)
Dim temp() As Long, i As Long, j As Long
If n = 1 Then
ReDim result(0)
result(0) = 1
End If
If n = 2 Then
ReDim result(3)
result(0) = 1
result(1) = 2
result(2) = 4
result(3) = 3
End If
If n > 2 Then
ReDim result(n ^ 2 - 1)
For i = 1 To n - 1
result(i - 1) = i
result(i * n - 1) = i + n - 1
result(n * n - i) = i + 2 * (n - 1)
result(n * n - i * n) = i + 3 * (n - 1)
Next
spiral n - 2, temp
For i = 0 To (n - 2) ^ 2 - 1
result(n + 1 + n * (i \ (n - 2)) + i Mod (n - 2)) = temp(i) + 4 * (n - 1)
Next
End If
End Sub
输出:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1
|
2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4
|
3
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1
|
2
|
3
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8
|
9
|
4
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7
|
6
|
5
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1
|
2
|
padding-right: 5.4pt; padding-left: 5.4pt; border-
发表评论
最新评论
|
评论