|
本帖最后由 aoe1981 于 2018-1-3 16:43 编辑
以下附件实现我在31楼里所说的“生成距离树”:
代码如下:
- Option Explicit
- Sub jlshu()
- Dim arr, brr, D_ljd As Object, B_jl As Object, t1$, t2$, i&, j&, k&, qd$, zd$, mbjl#, mblj$
- arr = Sheet2.Range("a1").CurrentRegion
- Set D_ljd = CreateObject("Scripting.Dictionary")
- Set B_jl = CreateObject("Scripting.Dictionary")
- For i = 2 To UBound(arr, 1) '将路径对应的距离,点的邻接表写入字典
- t1 = arr(i, 1): t2 = arr(i, 2)
- D_ljd(t1) = D_ljd(t1) & " " & t2 '点_邻接点
- D_ljd(t2) = D_ljd(t2) & " " & t1
- B_jl(t1 & "-" & t2) = arr(i, 3) '边_距离
- B_jl(t2 & "-" & t1) = arr(i, 3)
- Next i
- Dim D_jl As Object, D_lj As Object, U As Object, key1, key2, n&, gd, f_dian$, min_dian$, min_jl#, max_jl# '点的距离标记、路径标记、添加标记
- Set D_jl = CreateObject("Scripting.Dictionary")
- Set D_lj = CreateObject("Scripting.Dictionary")
- Set U = CreateObject("Scripting.Dictionary")
- key1 = D_ljd.keys: n = D_ljd.Count
- For i = 0 To n - 1 '初始化各点标记
- D_jl(key1(i)) = 0: D_lj(key1(i)) = key1(i)
- Next i
- max_jl = WorksheetFunction.Sum(B_jl.items) + 1: min_jl = max_jl
- qd = Sheet3.Range("a2").Value: zd = Sheet3.Range("b2").Value: U(qd) = 1 '首先添加根结点
- For i = 1 To n - 1 '至多添加其余n-1个点
- key1 = U.keys
- For j = 1 To U.Count '遍历U中每一点
- gd = Split(D_ljd(key1(j - 1)), " ")
- For k = 1 To UBound(gd) '扫描U中每一点的不属于U的邻接点
- If Not (U.exists(gd(k))) Then
- If D_jl(key1(j - 1)) + B_jl(key1(j - 1) & "-" & gd(k)) < min_jl Then '父点距离标记+路径距离
- f_dian = key1(j - 1): min_dian = gd(k): min_jl = D_jl(key1(j - 1)) + B_jl(key1(j - 1) & "-" & gd(k)) '寻找最短距离的点
- End If
- End If
- Next k
- Next j
- D_jl(min_dian) = min_jl '更新最短距离点的距离数据
- D_lj(min_dian) = D_lj(f_dian) & "-" & min_dian '记录最短距离点的路径数据:最短距离点&"-"&父点路径标记
- U(min_dian) = 1 '添加最短距离点
- min_jl = max_jl '每比较完一轮将最小距离重置为距离和+1
- Next i
- ReDim brr(1 To n, 1 To 2)
- key1 = D_jl.items: key2 = D_lj.items
- For i = 1 To n
- brr(i, 1) = key1(i - 1): brr(i, 2) = key2(i - 1)
- gd = Split(key2(i - 1), "-")
- If gd(UBound(gd)) = zd Then mbjl = brr(i, 1): mblj = brr(i, 2)
- Next i
- Sheet3.Range("a4:b" & Rows.Count).ClearContents
- Sheet3.Range("a4").Resize(n, 2).Value = brr
- MsgBox "起点" & qd & "到终点" & zd & "的最短距离是:" & mbjl & ",最短路径是:" & mblj
- End Sub
复制代码
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?免费注册
x
|