|
楼主 |
发表于 2014-11-22 13:43
|
显示全部楼层
两次 深度优先,迭代计算,数组模拟堆栈- Private aTree()
- Private aDist%()
- Private aCnt%()
- Private nSize%
- Public Function LongestPath(ByVal strTree As String) As Long
- Dim aData, i%, nA%, nB%, aLnk
- aData = Split(strTree, ";")
- nSize = CInt(aData(0))
- ReDim aTree(1 To nSize), aCnt(1 To nSize), aDist(1 To nSize)
- For i = 1 To nSize
- aTree(i) = aDist
- Next
- For i = 1 To UBound(aData)
- aLnk = Split(aData(i), ",")
- nA = aLnk(0)
- nB = aLnk(1)
- aCnt(nA) = aCnt(nA) + 1
- aCnt(nB) = aCnt(nB) + 1
- aTree(nA)(aCnt(nA)) = nB
- aTree(nB)(aCnt(nB)) = nA
- Next
- nA = DFS_Iterative(1)
- ReDim aDist(1 To nSize)
- nB = DFS_Iterative(nA)
- LongestPath = aDist(nB)
- Erase aTree: Erase aDist: Erase aCnt
- End Function
- Private Function DFS_Iterative%(nInd%)
- Dim i%, nCurInd%, nMaxLen%, nMaxInd%
- Dim aStack%(), nStackInd%
- ReDim aStack(1 To nSize, 1 To 2)
- aDist(nInd) = 1
- nStackInd = 1
- aStack(1, 1) = nInd
- aStack(1, 2) = 1
- Do
- nCurInd = aStack(nStackInd, 1)
- For i = aStack(nStackInd, 2) To aCnt(nCurInd)
- If aDist(aTree(nCurInd)(i)) = 0 Then Exit For
- Next
- If i > aCnt(nCurInd) Then
- nStackInd = nStackInd - 1
- Else
- nCurInd = aTree(nCurInd)(i)
- aDist(nCurInd) = nStackInd
- If nStackInd > nMaxLen Then nMaxLen = nStackInd: nMaxInd = nCurInd
- nStackInd = nStackInd + 1
- aStack(nStackInd, 1) = nCurInd
- aStack(nStackInd, 2) = 1
- aStack(nStackInd - 1, 2) = i + 1
- End If
- Loop Until nStackInd = 0
- DFS_Iterative = nMaxInd
- End Function
复制代码 |
|