'学习一下。邻接矩阵+深度搜索,,,
Option Explicit
Sub test()
Dim arr, i, first, n, dic, last, m
Set dic = CreateObject("scripting.dictionary")
arr = Sheets("题目").[a1].CurrentRegion
ReDim brr(UBound(arr, 1) * 2, UBound(arr, 1) * 2), crr(1 To 3, 1 To 100)
For i = 2 To UBound(arr, 1)
If Not dic.exists(arr(i, 1)) Then n = n + 1: dic(arr(i, 1)) = n: brr(n, 0) = arr(i, 1)
If Not dic.exists(arr(i, 2)) Then n = n + 1: dic(arr(i, 2)) = n: brr(n, 0) = arr(i, 2)
brr(dic(arr(i, 1)), dic(arr(i, 2))) = arr(i, 3)
brr(dic(arr(i, 2)), dic(arr(i, 1))) = arr(i, 3)
Next
ReDim flag(n), temp(1, n), result(1 To 1000, 1 To 3)
With Sheets("sheet1")
temp(0, 0) = .[a2].Value
first = dic(temp(0, 0)): last = dic(.[b2].Value)
Call dfs(brr, n, first, last, 1, flag, temp, result, m)
.[c2].Resize(Rows.Count - 1, 3).ClearContents
If m > 0 Then .[c2].Resize(m, 3) = result
End With
End Sub
Function dfs(brr, n, first, last, cnt, flag, temp, result, m)
Dim i, j, sum, s
If first = last Then
m = m + 1: result(m, 3) = cnt - 1
For j = 0 To cnt - 1
result(m, 2) = result(m, 2) & "->" & temp(0, j)
result(m, 1) = result(m, 1) + temp(1, j)
Next
result(m, 2) = Mid(result(m, 2), 3): Exit Function
End If
flag(first) = 1
For i = 1 To n
If flag(i) = 0 And brr(first, i) > 0 Then
temp(0, cnt) = brr(i, 0): temp(1, cnt) = brr(first, i)
dfs brr, n, i, last, cnt + 1, flag, temp, result, m
End If
Next
flag(first) = 0
End Function |