李同学设计了一个用来求两座岛屿之间相连所需桥的数量的VB程序,点击“生成矩阵”按钮Command1,随机产生一个关系矩阵,并在列表框List1中显示。在文本框Text1和Text2中输入岛屿的编号(1~9),点击“求解”按钮Command2,在Labell中输出两座岛屿之间相连所需桥的数量。VB程序运行界面如图所示。
对无桥相连的两座岛屿p1,p2之间相连的算法思想如下:
①p1岛屿所在行开始,将与其相连的岛屿依次添加到数组b中。
②若数组b中未出现岛屿p2,则依次查找与其相连岛屿的所在行,将新出现的相连的岛屿添加到数组b中。
③在查找过程中同时记录查找步数。
数组b内全部搜索完毕,若p2还是未出现,则两座岛屿之间无法相连,反之输出桥的数量。请回答以下问题:
Const n = 9 ‘岛屿的数量
Dim a(1 To n * n) As Integer
Private Sub Command1_Click()
Dim s As String List1.Clear
For i = 1 To n
For j = i To n
If j = i Then
a((i - 1) * n + j) = 0 ‘对角线为0
Else
a((i - 1) * n + j) = Int(Rnd * 2)
① ‘矩阵对称
End If
Next j Next i
For i = 1 To n
s = ""
For j = 1 To n
s = s + Str(a((i - 1) * n + j))
Next j
List1.AddItem s Next i
End Sub
Private Sub Command2_Click()
Dim b(1 To n) As Integer
Dim qiao(1 To n) As Integer ‘记录相连岛屿之间桥的数量
Dim find(1 To n) As Boolean ‘记录某岛屿是否被添加到数组b中
Dim p1 As Integer, p2 As Integer, cur As Integer, k As Integer, q As Integer
p1 = Val(Text1.Text)
p2 = Val(Text2.Text)
cur = p1: k = 1: q = 0
find(cur) = True
Do While find(p2) = False
For i = 1 To n
If a((cur - 1) * n + i) = 1 And find(i) = False Then
b(k) = i: k = k + 1
find(i) = True
②
End If
Next i
q = q + 1
If q = k Then Exit Do Else ③
Loop
If find(p2) = True Then
Label1.Caption = "需要经过" + Str(qiao(p2)) + "座桥"
Else
Label1.Caption = "无桥相连"
End If
End Sub
① ② ③