|
| 1 | +using Advanced.Algorithms.DataStructures; |
| 2 | +using Advanced.Algorithms.DataStructures.Graph.AdjacencyList; |
| 3 | +using System; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.Linq; |
| 6 | + |
| 7 | +namespace Advanced.Algorithms.Graph |
| 8 | +{ |
| 9 | + /// <summary> |
| 10 | + /// A* algorithm implementation using Fibornacci Heap. |
| 11 | + /// </summary> |
| 12 | + public class AStarShortestPath<T, W> where W : IComparable |
| 13 | + { |
| 14 | + readonly IShortestPathOperators<W> operators; |
| 15 | + readonly IAStarHeuristic<T, W> heuristic; |
| 16 | + |
| 17 | + public AStarShortestPath(IShortestPathOperators<W> operators, IAStarHeuristic<T, W> heuristic) |
| 18 | + { |
| 19 | + this.operators = operators; |
| 20 | + this.heuristic = heuristic; |
| 21 | + } |
| 22 | + |
| 23 | + /// <summary> |
| 24 | + /// Search path to target using the heuristic. |
| 25 | + /// </summary> |
| 26 | + public ShortestPathResult<T, W> FindShortestPath(WeightedDiGraph<T, W> graph, T source, T destination) |
| 27 | + { |
| 28 | + //regular argument checks |
| 29 | + if (graph?.FindVertex(source) == null || graph.FindVertex(destination) == null) |
| 30 | + { |
| 31 | + throw new ArgumentException(); |
| 32 | + } |
| 33 | + |
| 34 | + //track progress for distance to each Vertex from source |
| 35 | + var progress = new Dictionary<T, W>(); |
| 36 | + |
| 37 | + //trace our current path by mapping current vertex to its Parent |
| 38 | + var parentMap = new Dictionary<T, T>(); |
| 39 | + |
| 40 | + //min heap to pick next closest vertex |
| 41 | + var minHeap = new FibornacciMinHeap<AStarWrap<T, W>>(); |
| 42 | + //keep references of heap Node for decrement key operation |
| 43 | + var heapMapping = new Dictionary<T, AStarWrap<T, W>>(); |
| 44 | + |
| 45 | + //add vertices to min heap and progress map |
| 46 | + foreach (var vertex in graph.Vertices) |
| 47 | + { |
| 48 | + //init parent |
| 49 | + parentMap.Add(vertex.Key, default(T)); |
| 50 | + |
| 51 | + //init to max value |
| 52 | + progress.Add(vertex.Key, operators.MaxValue); |
| 53 | + |
| 54 | + if (vertex.Key.Equals(source)) |
| 55 | + { |
| 56 | + continue; |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + //start from source vertex as current |
| 61 | + var current = new AStarWrap<T, W>(heuristic, destination) |
| 62 | + { |
| 63 | + Distance = operators.DefaultValue, |
| 64 | + Vertex = source |
| 65 | + }; |
| 66 | + |
| 67 | + //insert neighbour in heap |
| 68 | + minHeap.Insert(current); |
| 69 | + heapMapping[source] = current; |
| 70 | + |
| 71 | + //until heap is empty |
| 72 | + while (minHeap.Count > 0) |
| 73 | + { |
| 74 | + //next min vertex to visit |
| 75 | + current = minHeap.ExtractMin(); |
| 76 | + heapMapping.Remove(current.Vertex); |
| 77 | + |
| 78 | + //no path exists, so return max value |
| 79 | + if (current.Distance.Equals(operators.MaxValue)) |
| 80 | + { |
| 81 | + return new ShortestPathResult<T, W>(null, operators.MaxValue); |
| 82 | + } |
| 83 | + |
| 84 | + //visit neighbours of current |
| 85 | + foreach (var neighbour in graph.Vertices[current.Vertex].OutEdges.Where(x => !x.Key.Value.Equals(source))) |
| 86 | + { |
| 87 | + //new distance to neighbour |
| 88 | + var newDistance = operators.Sum(current.Distance, |
| 89 | + graph.Vertices[current.Vertex].OutEdges[neighbour.Key]); |
| 90 | + |
| 91 | + //current distance to neighbour |
| 92 | + var existingDistance = progress[neighbour.Key.Value]; |
| 93 | + |
| 94 | + //update distance if new is better |
| 95 | + if (newDistance.CompareTo(existingDistance) < 0) |
| 96 | + { |
| 97 | + progress[neighbour.Key.Value] = newDistance; |
| 98 | + |
| 99 | + if (heapMapping.ContainsKey(neighbour.Key.Value)) |
| 100 | + { |
| 101 | + //decrement distance to neighbour in heap |
| 102 | + var decremented = new AStarWrap<T, W>(heuristic, destination) { Distance = newDistance, Vertex = neighbour.Key.Value }; |
| 103 | + minHeap.DecrementKey(heapMapping[neighbour.Key.Value], decremented); |
| 104 | + heapMapping[neighbour.Key.Value] = decremented; |
| 105 | + |
| 106 | + } |
| 107 | + else |
| 108 | + { |
| 109 | + //insert neighbour in heap |
| 110 | + var discovered = new AStarWrap<T, W>(heuristic, destination) { Distance = newDistance, Vertex = neighbour.Key.Value }; |
| 111 | + minHeap.Insert(discovered); |
| 112 | + heapMapping[neighbour.Key.Value] = discovered; |
| 113 | + } |
| 114 | + |
| 115 | + //trace parent |
| 116 | + parentMap[neighbour.Key.Value] = current.Vertex; |
| 117 | + } |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + return tracePath(graph, parentMap, source, destination); |
| 122 | + } |
| 123 | + |
| 124 | + /// <summary> |
| 125 | + /// Trace back path from destination to source using parent map. |
| 126 | + /// </summary> |
| 127 | + private ShortestPathResult<T, W> tracePath(WeightedDiGraph<T, W> graph, Dictionary<T, T> parentMap, T source, T destination) |
| 128 | + { |
| 129 | + //trace the path |
| 130 | + var pathStack = new Stack<T>(); |
| 131 | + |
| 132 | + pathStack.Push(destination); |
| 133 | + |
| 134 | + var currentV = destination; |
| 135 | + while (!Equals(currentV, default(T)) && !Equals(parentMap[currentV], default(T))) |
| 136 | + { |
| 137 | + pathStack.Push(parentMap[currentV]); |
| 138 | + currentV = parentMap[currentV]; |
| 139 | + } |
| 140 | + |
| 141 | + //return result |
| 142 | + var resultPath = new List<T>(); |
| 143 | + var resultLength = operators.DefaultValue; |
| 144 | + while (pathStack.Count > 0) |
| 145 | + { |
| 146 | + resultPath.Add(pathStack.Pop()); |
| 147 | + } |
| 148 | + |
| 149 | + for (int i = 0; i < resultPath.Count - 1; i++) |
| 150 | + { |
| 151 | + resultLength = operators.Sum(resultLength, |
| 152 | + graph.Vertices[resultPath[i]].OutEdges[graph.Vertices[resultPath[i + 1]]]); |
| 153 | + } |
| 154 | + |
| 155 | + return new ShortestPathResult<T, W>(resultPath, resultLength); |
| 156 | + } |
| 157 | + } |
| 158 | + |
| 159 | + /// <summary> |
| 160 | + /// Search heuristic used by A* search algorithm. |
| 161 | + /// </summary> |
| 162 | + public interface IAStarHeuristic<T, W> where W : IComparable |
| 163 | + { |
| 164 | + /// <summary> |
| 165 | + /// Return the distance to target for given sourcevertex as computed by the hueristic used for A* search. |
| 166 | + /// </summary> |
| 167 | + W HueristicDistanceToTarget(T sourceVertex, T targetVertex); |
| 168 | + } |
| 169 | + |
| 170 | + //Node for our Fibornacci heap |
| 171 | + internal class AStarWrap<T, W> : IComparable where W : IComparable |
| 172 | + { |
| 173 | + private IAStarHeuristic<T, W> heuristic; |
| 174 | + private T destinationVertex; |
| 175 | + internal AStarWrap(IAStarHeuristic<T, W> heuristic, T destinationVertex) |
| 176 | + { |
| 177 | + this.heuristic = heuristic; |
| 178 | + this.destinationVertex = destinationVertex; |
| 179 | + } |
| 180 | + |
| 181 | + internal T Vertex { get; set; } |
| 182 | + internal W Distance { get; set; } |
| 183 | + |
| 184 | + //compare distance to target using the heuristic provided |
| 185 | + public int CompareTo(object obj) |
| 186 | + { |
| 187 | + if (this == obj) |
| 188 | + { |
| 189 | + return 0; |
| 190 | + } |
| 191 | + |
| 192 | + var result1 = heuristic.HueristicDistanceToTarget(Vertex, destinationVertex); |
| 193 | + var result2 = heuristic.HueristicDistanceToTarget((obj as AStarWrap<T, W>).Vertex, destinationVertex); |
| 194 | + |
| 195 | + return result1.CompareTo(result2); |
| 196 | + } |
| 197 | + } |
| 198 | +} |
0 commit comments