|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
本帖最后由 aoe1981 于 2017-11-18 23:28 编辑
老师,给您发消息您不回,我按我的理解做完了,如果有问题,烦您提前通知下,我思考修改。
代码如下:
- Option Explicit
- Dim brr(), qd$, zd$, m&, jg(1 To 9999, 1 To 2), k%
- Sub LuJing()
- Sheet1.Range("c2:d" & Rows.Count).ClearContents
- Dim arr(), i&
- arr = Sheet2.Range("a2:c13").Value
- m = UBound(arr())
- brr = Application.Transpose(arr)
- ReDim Preserve brr(1 To UBound(arr(), 2), 1 To m * 2)
- brr = Application.Transpose(brr)
- For i = 1 To m
- brr(m + i, 1) = arr(i, 2): brr(m + i, 2) = arr(i, 1): brr(m + i, 3) = arr(i, 3)
- Next i
- m = UBound(brr(), 1)
- qd = Sheet1.Range("a2").Value: zd = Sheet1.Range("b2").Value
- Call DG(qd, qd, 0)
- Sheet1.Range("c2").Resize(k, 2).Value = jg()
- End '释放全局变量,防止重复点击重复记录
- End Sub
- Sub DG(dian, lu, jl)
- Dim j&, crr(), n&
- ReDim crr(1 To m, 1 To 3)
- For j = 1 To m '筛选当前点的下一步路径
- If brr(j, 1) = dian Then n = n + 1: crr(n, 1) = brr(j, 1): crr(n, 2) = brr(j, 2): crr(n, 3) = brr(j, 3)
- Next j
- For j = 1 To UBound(crr, 1)
- If crr(j, 2) = "" Then lu = Replace(lu, "-" & crr(j - 1, 1), ""): jl = jl - crr(j - 1, 3): Exit Sub '某一点遍历完后取消连接返回上一点
- If InStr(lu, crr(j, 2)) = 0 Then '形成圈时取消连接,否则继续向下连接
- lu = lu & "-" & crr(j, 2)
- jl = jl + crr(j, 3)
- If crr(j, 2) <> zd Then
- Call DG(crr(j, 2), lu, jl)
- Else '到达终点时记录并退出
- k = k + 1: jg(k, 2) = lu: lu = Replace(lu, "-" & crr(j, 2), ""): jg(k, 1) = jl: jl = jl - crr(j, 3)
- End If
- End If
- Next j
- End Sub
复制代码 附件如下:
修改后的代码如下(以上附件同步更新):
- Option Explicit
- Dim brr(), qd$, zd$, m&, jg(1 To 9999, 1 To 2), k&
- Sub LuJing()
- Sheet1.Range("c2:e" & Rows.Count).ClearContents
- Dim arr(), i&
- arr = Sheet2.Range("a2:c13").Value
- m = UBound(arr)
- brr = Application.Transpose(arr)
- ReDim Preserve brr(1 To UBound(arr, 2), 1 To m * 2)
- brr = Application.Transpose(brr)
- For i = 1 To m
- brr(m + i, 1) = arr(i, 2): brr(m + i, 2) = arr(i, 1): brr(m + i, 3) = arr(i, 3)
- Next i
- m = UBound(brr, 1)
- qd = Sheet1.Range("a2").Value: zd = Sheet1.Range("b2").Value
- If qd <> zd Then Call DG(qd, qd, 0) Else k = 1: jg(k, 1) = 0: jg(k, 2) = qd & "-" & zd
- Sheet1.Range("c2").Resize(k, 2).Value = jg()
- End '释放全局变量,防止重复点击重复记录
- End Sub
- Sub DG(dian, lu, jl)
- Dim j&, crr(), n&
- ReDim crr(1 To m, 1 To 3)
- For j = 1 To m '筛选当前点的下一步路径
- If brr(j, 1) = dian Then n = n + 1: crr(n, 1) = brr(j, 1): crr(n, 2) = brr(j, 2): crr(n, 3) = brr(j, 3)
- Next j
- For j = 1 To UBound(crr, 1)
- If crr(j, 2) = "" Then Exit Sub '某一点遍历完后返回上一点
- If InStr(lu, crr(j, 2)) = 0 Then '形成圈时取消连接,否则继续向下连接
- lu = lu & "-" & crr(j, 2)
- jl = jl + crr(j, 3)
- If crr(j, 2) <> zd Then
- Call DG(crr(j, 2), lu, jl)
- Else '到达终点时记录路径和距离
- k = k + 1: jg(k, 2) = lu: jg(k, 1) = jl
- End If
- lu = Replace(lu, "-" & crr(j, 2), ""): jl = jl - crr(j, 3)'下一点递归调用后未找到路径时(遍历后都形成圈且未达终点),返回本层执行取消连接操作;本层到达终点后取消最后一步连接,继续寻找新的路径
- End If
- Next j
- End Sub
复制代码
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?免费注册
x
评分
-
1
查看全部评分
-
|