VB二维数组编程
n=3时输出1 8 7
2 9 6
3 4 5
N是用INPUTBOX输入的
答案:我来个另类的呵呵,碰撞检测法完成这个题目,我的代码在VS2008里调试通过,代码需要在VS2003以上版本运行,VB6由于有些关键字不支持无法运行。
Public Class Form1
Private Enum PathFollow
上 = 1
下 = 2
左 = 3
右 = 4
End Enum
Private m_Out(,) As Integer
Private Sub FillNum(ByVal StartNum As Integer, ByVal X As Integer, ByVal Y As Integer, ByVal n As Integer, ByVal Follow As PathFollow)
'假如数字已大于边长的平方或边长小于2则结束递归调用
If StartNum > n ^ 2 Or n < 2 Then Exit Sub
'判断方向确定数字如何填充入数组
Select Case Follow
Case PathFollow.上
'假如Y坐标未超出边界且要填充的数组元素为0则将数字填入该数组元素,否则改变方向为左
If Y - 1 >= 0 AndAlso m_Out(X, Y - 1) = 0 Then
Y -= 1
m_Out(X, Y) = StartNum
StartNum += 1
Else
Follow = PathFollow.左
End If
Case PathFollow.下
'假如Y坐标未超出边界且要填充的数组元素为0则将数字填入该数组元素,否则改变方向为右
If Y + 1 <= n - 1 AndAlso m_Out(X, Y + 1) = 0 Then
Y += 1
m_Out(X, Y) = StartNum
StartNum += 1
Else
Follow = PathFollow.右
End If
Case PathFollow.左
'假如X坐标未超出边界且要填充的数组元素为0则将数字填入该数组元素,否则改变方向为下
If X - 1 >= 0 AndAlso m_Out(X - 1, Y) = 0 Then
X -= 1
m_Out(X, Y) = StartNum
StartNum += 1
Else
Follow = PathFollow.下
End If
Case PathFollow.右
'假如X坐标未超出边界且要填充的数组元素为0则将数字填入该数组元素,否则改变方向为上
If X + 1 <= n - 1 AndAlso m_Out(X + 1, Y) = 0 Then
X += 1
m_Out(X, Y) = StartNum
StartNum += 1
Else
Follow = PathFollow.上
End If
End Select
'递归调用
Call FillNum(StartNum, X, Y, n, Follow)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Num As Integer
Dim i As Integer
Dim j As Integer
Dim s As String = ""
'输入一个整数
Num = Fix(Val(InputBox("请输入一个整数")))
If Num < 2 Then
MsgBox("输入的数字不合法,无法完成运算", MsgBoxStyle.Critical, "错误")
Exit Sub
End If
ReDim m_Out(Num, Num)
'调用函数填充数组
Call FillNum(1, 0, -1, Num, PathFollow.下)
'输入数组内容
For i = 0 To Num - 1
For j = 0 To Num - 1
s &= " " & m_Out(j, i)
Next
Debug.Print(s)
s = ""
Next
End Sub
End Class
'加入一个command控件
Option Explicit
Dim arr(), m
Private Sub Command1_Click()
Dim n, i, j
n = InputBox("输入一个有效的数字:")
If Not IsNumeric(n) Or n = "0" Then
MsgBox "无效数字!"
Exit Sub
End If
n = Val(n) '转换为数值
ReDim arr(1 To n, 1 To n)
m = 0
fc 1, n
Cls
For i = 1 To n '输出到form
For j = 1 To n
Print arr(i, j),
Next
Next
End Sub
Function fc(a, b)
Dim i, j
If a > b Then Exit Function '结束递归调用
For i = a To b '左下
m = m + 1
arr(i, UBound(arr) - b + 1) = m
Next
For i = a + 1 To b '下右
m = m + 1
arr(b, i) = m
Next
For i = b - 1 To a Step -1 '右上
m = m + 1
arr(i, b) = m
Next
For i = b - 1 To a + 1 Step -1 '上右
m = m + 1
arr(a, i) = m
Next
fc a + 1, b - 1 '递归调用
End Func