A* Exercise (Solution)

 Public Function AStar(start As Integer, destination As Integer) As List(Of String)
 Dim openVertices As New List(Of Integer) 'this list is the fringe
 Dim closedVertices As New List(Of Integer)
 Dim unvisitedVertices As New List(Of Integer)
 Dim currentVertex As Vertex

 'all vertices are unvisited to begin with
 For i As Integer = 0 To TOTAL_VERTICES - 1
     unvisitedVertices.Add(i)
 Next

 'make the start vertex current
 unvisitedVertices.Remove(start)
 currentVertex = vertices(start)

 'calculate f value for start vertex (g + h)
 vertices(start).g = 0
 vertices(start).f = vertices(start).g + vertices(start).h(vertices(destination))

 While currentVertex IsNot vertices(destination)

     'for each vertex adjacent to current
     For i As Integer = 0 To TOTAL_VERTICES - 1
         If adjacencyMatrix(currentVertex.Index, i) > 0 Then 'it's a neighbour if it shares an edge 

             'if it's not in closed list and not in open list
             If (Not (closedVertices.Contains(i))) And (Not (openVertices.Contains(i))) Then
                 unvisitedVertices.Remove(i)
                 openVertices.Add(i)
                 vertices(i).Parent = currentVertex
             End If

             'calculate the f value for all open neighbours
             Dim g As Integer
             Dim f As Integer
             g = currentVertex.g + adjacencyMatrix(currentVertex.Index, i)
             f = g + vertices(i).h(vertices(destination))

             'update the f value if it is brand new (existing value is 0) 
             'or new value is smaller than existing value
             If (vertices(i).f = 0) Or (f < vertices(i).f) Then
                 vertices(i).f = f
                 vertices(i).g = g
                 vertices(i).Parent = currentVertex
             End If

         End If
     Next

     closedVertices.Add(currentVertex.Index)

     'remove vertex with lowest f value from open list and make it current
     Dim iSmallestf As Integer = 1000 'large value to start
     Dim iNextCurrent As Integer
     For Each i In openVertices
         If vertices(i).f < iSmallestf Then
             iSmallestf = vertices(i).f
             iNextCurrent = i
         End If
     Next
     openVertices.Remove(iNextCurrent)
     currentVertex = vertices(iNextCurrent)

 End While

 'generate the path information

 ''reverse of path 
 'MsgBox(vertices(destination).Parent.Value)
 'MsgBox(vertices(destination).Parent.Parent.Value)
 'MsgBox(vertices(destination).Parent.Parent.Parent.Value)
 'MsgBox(vertices(destination).Parent.Parent.Parent.Parent.Value)

 Dim shortestpath As New List(Of String)

 Dim v As Vertex
 v = vertices(destination)
 Do Until v Is Nothing
     shortestpath.Add(v.Value)
     v = v.Parent
 Loop

 shortestpath.Reverse()

 shortestpath.Add(currentVertex.g) 'returns length of path as a string

 Return shortestpath

 End Function