|
1 | 1 | using System; |
2 | 2 | using System.Collections.Generic; |
3 | 3 | using System.Diagnostics; |
| 4 | +using System.Linq; |
4 | 5 |
|
5 | 6 | namespace MLEM.Pathfinding { |
6 | 7 | /// <summary> |
@@ -86,11 +87,12 @@ public bool TryFindPath(T start, ICollection<T> goals, out Stack<T> path, out fl |
86 | 87 | var tries = maxTries ?? this.DefaultMaxTries; |
87 | 88 | var defCost = defaultCost ?? this.DefaultCost; |
88 | 89 | var additional = additionalNeighbors ?? this.DefaultAdditionalNeighbors; |
| 90 | + var goalArray = goals as T[] ?? goals.ToArray(); |
89 | 91 |
|
90 | 92 | var neighbors = new HashSet<T>(); |
91 | 93 | var open = new Dictionary<T, PathPoint<T>>(); |
92 | 94 | var closed = new Dictionary<T, PathPoint<T>>(); |
93 | | - open.Add(start, new PathPoint<T>(start, this.GetMinHeuristicDistance(start, goals), null, 0, defCost)); |
| 95 | + open.Add(start, new PathPoint<T>(start, this.GetMinHeuristicDistance(start, goalArray), null, 0, defCost)); |
94 | 96 |
|
95 | 97 | var count = 0; |
96 | 98 | while (open.Count > 0) { |
@@ -118,7 +120,7 @@ public bool TryFindPath(T start, ICollection<T> goals, out Stack<T> path, out fl |
118 | 120 | foreach (var neighborPos in neighbors) { |
119 | 121 | var cost = getCost(current.Pos, neighborPos); |
120 | 122 | if (!float.IsPositiveInfinity(cost) && cost < float.MaxValue && !closed.ContainsKey(neighborPos)) { |
121 | | - var neighbor = new PathPoint<T>(neighborPos, this.GetMinHeuristicDistance(neighborPos, goals), current, cost, defCost); |
| 123 | + var neighbor = new PathPoint<T>(neighborPos, this.GetMinHeuristicDistance(neighborPos, goalArray), current, cost, defCost); |
122 | 124 | // check if we already have a waypoint at this location with a worse path |
123 | 125 | if (open.TryGetValue(neighborPos, out var alreadyNeighbor)) { |
124 | 126 | if (neighbor.G < alreadyNeighbor.G) { |
@@ -160,10 +162,10 @@ public bool TryFindPath(T start, ICollection<T> goals, out Stack<T> path, out fl |
160 | 162 | /// <param name="neighbors">The set to populate with neighbors.</param> |
161 | 163 | protected abstract void CollectNeighbors(T position, ISet<T> neighbors); |
162 | 164 |
|
163 | | - private float GetMinHeuristicDistance(T start, IEnumerable<T> positions) { |
| 165 | + private float GetMinHeuristicDistance(T start, T[] positions) { |
164 | 166 | var min = float.MaxValue; |
165 | | - foreach (var position in positions) |
166 | | - min = Math.Min(min, this.GetHeuristicDistance(start, position)); |
| 167 | + for (var i = 0; i < positions.Length; i++) |
| 168 | + min = Math.Min(min, this.GetHeuristicDistance(start, positions[i])); |
167 | 169 | return min; |
168 | 170 | } |
169 | 171 |
|
|
0 commit comments