<B>最短路径算法源码(VB)</B>
< > 本人载网站开发gis,游自编的最短路径查询程序,速度特快,3万节点,35000条路全部遍历,只需1秒。现将最短路径的思路告诉大家,希望大家在优化,并用不同语言编制,我正在学delphi,准备用delphi做成库,本例以由拓扑关系的arc/info 文件为数据源。其中a1,b1,c1是以fnode排序生成的数组,a1对应fnode,b1对应tnode,c1对应length,同样a2,b2,c2,是以tnode 生成的数组。Indexa1是对应某一起点与其相连的终点的个数,indexb1时对应某一终点与其相连的起点的个数,即其拓扑关系。
Public Function shortpath(startno As Integer, endno As Integer) As Single
以开始点,结束点为参数。
Dim result() As Single
Dim result1 As Integer
定义结果点
Dim s1 As Single
Dim min As Single
Dim ii, i, j, aa As Integer
Dim yc() As Boolean
Dim ycd() As Boolean
Dim rs1() As Single
Dim no() As Integer
Dim nopoint As Integer
ReDim yc(1 To maxno) As Boolean
ReDim ycd(1 To maxno) As Boolean
ReDim rs1(1 To maxno) As Single
ReDim result(1 To 2, 1 To maxno) As Single
定义结果,其中result(1,maxno)为结果点,result(2,maxno)为结果长度。
For i = 1 To maxno// maxno为网中最大的节点数。
yc(i) = False //标记已经查过的点。
ycd(i) = False //标记已经作结果点用过的点
rs1(i) = 1E+38 //假设从起点到任一点的距离都为无穷大
Next i
ll = startno //设置开始点。
yc(ll) = True //标记开始点为真。即已经作结果点用过。
j = 0
For aa = 1 To maxno
先从与开始点相连的终点寻找
For i = 1 To indexa1(2, ll) //以与ll点相连的起点的个数循环
result1 = b1(indexa1(1, ll) - i + 1)找出与LL点相连的终点的点号
s1 = c1(indexa1(1, ll) - i + 1) + result(2, ll)找出长度并求和
If yc(result1) = True Then GoTo 200如果以被经查过进行下一个
If ycd(result1) = True Then//如果已经作为结果点判断哪一个长
If rs1(result1) >= s1 Then//如果这一点到起点的长度比现在的路线长,替代
rs1(result1) = s1
result(1, result1) = ll//设置到这点的最短路径的前一点为LL点(精华部分)
result(2, result1) = s1设置到这点的最短路径长度
GoTo 200
Else
GoTo 200
End If
End If
如果上面的条件都不符合则进行下面的语句
ycd(result1) = True
rs1(result1) = s1
result(1, result1) = ll
result(2, result1) = s1
每找到一个点加一,为了下面的判断
j = j + 1
ReDim Preserve no(1 To j) As Integer
从新 定义数组并使其值为当前的点号
no(j) = result1
200 Next I
再从与开始点相连的终点寻找,与上面一样不再标注
For i = 1 To indexb2(2, ll)
result1 = a2(indexb2(1, ll) - i + 1)
s1 = c2(indexb2(1, ll) - i + 1) + result(2, ll)
If yc(result1) = True Then GoTo 300
If ycd(result1) = True Then
If rs1(result1) >= s1 Then
rs1(result1) = s1
result(1, result1) = ll
result(2, result1) = s1
GoTo 300
Else
GoTo 300
End If
End If
ycd(result1) = True
rs1(result1) = s1
result(1, result1) = ll
result(2, result1) = s1
j = j + 1
ReDim Preserve no(1 To j) As Integer
no(j) = result1
300 Next I
设置最小为无穷大,最短路径点为空
min = 1E+38
minpoint = Null
(优化部分)
找出已经查过点中长度最短的点
For i = aa To j
If min > rs1(no(i)) Then
ii = i
min = rs1(no(i))
minpoint = no(i)
End If
Next I
如果没有结果,即起点与终点没有通路退出程序
If min = 1E+38 Then Exit Function
(重点优化)将两点互换,减少循环。
no(ii) = no(aa)
no(aa) = minpoint
标记已经作为结果点判断过
yc(minpoint) = True
ll = minpoint
判断结果点是否等于终点,如果等于则已经找到最短路径
If minpoint = endno Then Exit For
Next aa
返回最短路径长度
Stpath = result(2, endno)
End Function </P> |